Python datetime module

17 Nov, 2021
In Python, date and time are not a data type of their own, but a module named datetime can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. 
Python Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. 
The DateTime module is categorized into 6 main classes – 
date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month and day.
time – An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
tzinfo – It provides time zone information objects.
timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version 3.2).
The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.
Constructor syntax:  
class datetime.date(year, month, day)
The arguments must be in the following range –  
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
Note – If the argument is not an integer it will raise a TypeError and if it is outside the range a ValueError will be raised. 
Python3
# Python program to# demonstrate date class # import the date classfrom datetime import date # initializing constructor# and passing arguments in the# format year, month, datemy_date = date(1996, 12, 11) print("Date passed as argument is", my_date) # Uncommenting my_date = date(1996, 12, 39)# will raise an ValueError as it is# outside range # uncommenting my_date = date('1996', 12, 11)# will raise a TypeError as a string is# passed instead of integer
Output: 
Date passed as argument is 1996-12-11
Traceback (most recent call last):
  File "/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py", line 14, in 
    my_date = date(1996, 12, 39)
ValueError: day is out of range for month

Traceback (most recent call last):
  File "/home/53b974e10651f1853eee3c004b48c481.py", line 18, in 
    my_date = date('1996', 12, 11)
TypeError: an integer is required (got type str) 
To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually. 
Python3
# Python program to# print current date from datetime import date # calling the today# function of date classtoday = date.today() print("Today's date is", today)
Today's date is 2021-08-19
We can get the year, month, and date attributes from the date object using the year, month and date attribute of the date class.
Python3
from datetime import date # date object of today's datetoday = date.today() print("Current year:", today.year)print("Current month:", today.month)print("Current day:", today.day)
Current year: 2021
Current month: 8
Current day: 19
We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp is the number of seconds from 1st January 1970 at UTC to a particular date.
Python3
from datetime import datetime # Getting Datetime from timestampdate_time = datetime.fromtimestamp(1887639468)print("Datetime from timestamp:", date_time)
Datetime from timestamp: 2029-10-25 16:17:48
We can convert date object to a string representation using two functions isoformat() and strftime().
Python3
from datetime import date   # calling the today# function of date classtoday = date.today()   # Converting the date to the stringStr = date.isoformat(today)print("String Representation", Str)print(type(Str))
String Representation 2021-08-19
<class 'str'>
The time class creates the time object which represents local time, independent of any day. 
Constructor Syntax: 
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
All the arguments are optional. tzinfo can be None otherwise all the attributes must be integer in the following range – 
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
fold in [0, 1]
Python3
# Python program to# demonstrate time class from datetime import time # calling the constructormy_time = time(13, 24, 56) print("Entered time", my_time) # calling constructor with 1# argumentmy_time = time(minute=12)print("\nTime with one argument", my_time) # Calling constructor with# 0 argumentmy_time = time()print("\nTime without argument", my_time) # Uncommenting time(hour = 26)# will rase an ValueError as# it is out of range # uncommenting time(hour ='23')# will raise TypeError as# string is passed instead of int
Output: 
Entered time 13:24:56

Time with one argument 00:12:00

Time without argument 00:00:00
Traceback (most recent call last):
  File "/home/95ff83138a1b3e67731e57ec6dddef25.py", line 21, in 
    print(time(hour=26))
ValueError: hour must be in 0..23

Traceback (most recent call last):
  File "/home/fcee9ba5615b0b74fc3ba39ec9a789fd.py", line 21, in 
    print(time(hour='23'))
TypeError: an integer is required (got type str)
After creating a time object, its attributes can also be printed separately. 
Python3
from datetime import time Time = time(11, 34, 56) print("hour =", Time.hour)print("minute =", Time.minute)print("second =", Time.second)print("microsecond =", Time.microsecond)
Output: 
hour = 11
minute = 34
second = 56
microsecond = 0
We can convert time object to string using the isoformat() method.
Python3
from datetime import time # Creating Time objectTime = time(12,24,36,1212) # Converting Time object to stringStr = Time.isoformat()print("String Representation:", Str)print(type(Str))
String Representation: 12:24:36.001212
<class 'str'>
The DateTime class contains information on both date and time. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day.
Constructor Syntax: 
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)  
The year, month and day arguments are mandatory. tzinfo can be None, rest all the attributes must be an integer in the following range –  
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
fold in [0, 1]
Note – Passing an argument other than integer will raise a TypeError and passing arguments outside the range will raise ValueError.
Python3
# Python program to# demonstrate datetime object from datetime import datetime # Initializing constructora = datetime(1999, 12, 12)print(a) # Initializing constructor# with time parameters as wella = datetime(1999, 12, 12, 12, 12, 12, 342380)print(a)
Output: 
1999-12-12 00:00:00
1999-12-12 12:12:12.342380
After creating a DateTime object, its attributes can also be printed separately.
Python3
from datetime import datetime a = datetime(1999, 12, 12, 12, 12, 12) print("year =", a.year)print("month =", a.month)print("hour =", a.hour)print("minute =", a.minute)print("timestamp =", a.timestamp())
Output: 
year = 1999
month = 12
hour = 12
minute = 12
timestamp = 945000732.0
You can print the current date and time using the Datetime.now() function. now() function returns the current local date and time. 
Python3
from datetime import datetime # Calling now() functiontoday = datetime.now() print("Current date and time is", today)
Output: 
Current date and time is 2019-10-25 11:12:11.289834
We can convert Datetime to string in Python using the datetime.strftime and datetime.isoformat methods. 
Python3
from datetime import datetime as dt # Getting current date and timenow = dt.now() string = dt.isoformat(now)print(string)print(type(string))
2021-08-19T18:13:25.346259
<class 'str'>
Python timedelta class is used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
Constructor syntax:  
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)Returns : Date 
Python3
# Timedelta function demonstration from datetime import datetime, timedelta  # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint("initial_date", str(ini_time_for_now)) # Calculating future dates# for two yearsfuture_date_after_2yrs = ini_time_for_now + timedelta(days=730) future_date_after_2days = ini_time_for_now + timedelta(days=2) # printing calculated future_datesprint('future_date_after_2yrs:', str(future_date_after_2yrs))print('future_date_after_2days:', str(future_date_after_2days))
Output: 
initial_date 2019-10-25 12:01:01.227848
future_date_after_2yrs: 2021-10-24 12:01:01.227848
future_date_after_2days: 2019-10-27 12:01:01.227848
Date and Time difference can also be found using this class.
Python3
# Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint("initial_date", str(ini_time_for_now)) # Some another datetimenew_final_time = ini_time_for_now + \    timedelta(days=2) # printing new final_dateprint("new_final_time", str(new_final_time))  # printing calculated past_datesprint('Time difference:', str(new_final_time -                              ini_time_for_now))
Output: 
initial_date 2019-10-25 12:02:32.799814
new_final_time 2019-10-27 12:02:32.799814
Time difference: 2 days, 0:00:00
Formatting Datetime can be very necessary as the date representation may differe from place to place. Like in some countries it can be yyyy-mm-dd and in other country it can be dd-mm-yyyy. To format Python Datetime strptime and strftime functions can be used.
strftime() method converts the given date, time or datetime object to the a string representation of the given format.
Python3
# Python program to demonstrate# strftime() function  from datetime import datetime as dt # Getting current date and timenow = dt.now()print("Without formatting", now) # Example 1s = now.strftime("%A %m %-Y")print('\nExample 1:', s) # Example 2s = now.strftime("%a %-m %y")print('\nExample 2:', s) # Example 3s = now.strftime("%-I %p %S")print('\nExample 3:', s) # Example 4s = now.strftime("%H:%M:%S")print('\nExample 4:', s)
Without formatting 2021-08-19 18:16:25.881661

Example 1: Thursday 08 2021

Example 2: Thu 8 21

Example 3: 6 PM 25

Example 4: 18:16:25
Note: For more information, refer to strftime() method.
strptime() creates a datetime object from the given string.
Python3
# import datetime module from datetimefrom datetime import datetime  # consider the time stamps from a list  in string# format DD/MM/YY H:M:S.microstime_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003",             "27/05/99 07:35:5.523", "28/05/99 05:15:55.523"]  # format the string in the given format : day/month/year # hours/minutes/seconds-micro secondsformat_data = "%d/%m/%y %H:%M:%S.%f"  # Using strptime with datetime we will format string# into datetimefor i in time_data:    print(datetime.strptime(i, format_data))
1999-05-25 02:35:08.023000
1999-05-26 12:45:00.003000
1999-05-27 07:35:05.523000
1999-05-28 05:15:55.523000
Timezones in DateTime can be used in the case where one might want to display time according to the timezone of a specific region. This can be done using the pytz module of Python. This module serves the date-time conversion functionalities and helps users serving international client bases.
Python3
from datetime import datetimefrom pytz import timezone format = "%Y-%m-%d %H:%M:%S %Z%z" # Current time in UTCnow_utc = datetime.now(timezone('UTC'))print(now_utc.strftime(format)) timezones = ['Asia/Kolkata', 'Europe/Kiev', 'America/New_York'] for tzone in timezones:     # Convert to Asia/Kolkata time zone    now_asia = now_utc.astimezone(timezone(tzone))    print(now_asia.strftime(format))
2021-08-19 18:27:28 UTC+0000
2021-08-19 23:57:28 IST+0530
2021-08-19 21:27:28 EEST+0300
2021-08-19 14:27:28 EDT-0400
arorakashish0911
simranarora5sos
nikhilaggarwal3
sweetyty
kalrap615
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts