Dremendo Tag Line

Datetime Module in Python Programming

Modules in Python

In this lesson, we will understand what is Datetime module and how to implement them in Python Programming along with some examples.

What is Datetime Module in Python?

The datetime module contains classes used in the python program for manipulating dates and times. The most important classes in the datetime module are date, time, datetime, and timedelta.

Let's see the various implementation of the important classes of the datetime module using multiple examples.

video-poster

Date Class of DateTime Module

The date class of the datetime module is used to create a date object that represents the date in the format YYYY-MM-DD. The essential methods and attributes of the date class are:

  • today()
  • day, month, year
  • date()
  • isoformat()
  • fromisoformat()
  • isoweekday()
  • isocalendar()
  • strftime()

Let's see the use of the above methods and attributes of the date class with examples.

Get Current Date

We can get the current date by calling the today() method of the date class. The today() method will return the date in the format YYYY-MM-DD.

Example

from datetime import date

dt = date.today()
print(dt)

Output

2022-08-02

Get Current Day, Month and Year

We can get the current day, month and year by calling the day, month and year attributes of the date class.

Example

from datetime import date

dt = date.today()
print('Day:',dt.day)
print('Month:',dt.month)
print('Year:',dt.year)

Output

Day: 2
Month: 8
Year: 2022

Create Date Object From Valid Integers

We can create a date object from valid integers using the date() constructor of the date class.

Example

from datetime import date

dt = date(2022, 5, 28)
print('Day =',dt.day)
print('Month =',dt.month)
print('Year =',dt.year)

Output

Day = 28
Month = 5
Year = 2022

Convert Date into String

We can convert a date into a string by calling the isoformat() method of the date class.

Example

from datetime import date

dt = date.today()
st = dt.isoformat()
print(st)

Output

2022-08-02

Convert String Representation of Date into Date Object

We can convert a date from a string format YYYY-MM-DD into a date object by calling the fromisoformat() method of the date class.

Example

from datetime import date

st = '2022-08-02'
dt = date.fromisoformat(st)
print('Day =',dt.day)
print('Month =',dt.month)
print('Year =',dt.year)

Output

Day = 2
Month = 8
Year = 2022

Get Weekday as Integer From Date Object

We can get the weekday as an integer from a date by calling the isoweekday() method of the date class that returns the weekday as an integer where Monday represents 1 and Sunday represents 7.

Example

from datetime import date

day = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
st = '2022-07-20'
dt = date.fromisoformat(st)
wd = dt.isoweekday()
print("Weekday on 20th July 2022 = %d %s" %(wd, day[wd-1]))

Output

Weekday on 20th July 2022 = 3 Wednesday

Get Year, Week, Weekday From Date Object

We can get the year, week, and weekday from a date by calling the isocalendar() method of the date class that returns a tuple containing year, week, and weekday.

Example

from datetime import date

st = '2022-07-20'
dt = date.fromisoformat(st)
x = dt.isocalendar()
print(x)
print('Year =', x[0])
print('Week =', x[1])
print('Weekday =', x[2])

Output

(2022, 29, 3)
Year = 2022
Week = 29
Weekday = 3

Format Date

We can format a date using the strftime() method of the date class that returns the string representation of the formatted date.

Below is the list of format codes used for formatting the date object.

Format Code Meaning Example
%a Day short name. Mon, Tue, Wed...
%A Day full name. Monday, Tuesday, Wednesday...
%d Day of the month with a leading 0. 01, 02, 03...
%b Month short name. Jan, Feb, Apr...
%B Month full name January, February, March...
%m Month as number with a leading 0. 01, 02, 03
%y Year short format 20, 21, 22...
%Y Year full format 2020, 2021, 2022...
%j Day of the year with leading zero. 001, 020, 138, 256, 365...
%U Week number of the year where sunday is the first day of the week with leading zero. All days in the new year preceding the first sunday is considered to be in week 0. 00, 08, 27, 49...
%W Week number of the year where monday is the first day of the week with leading zero. All days in the new year preceding the first monday is considered to be in week 0. 00, 08, 27, 49...

Example

from datetime import date

dt = date(2022, 8, 15)
st1 = dt.strftime('%d/%m/%Y')
st2 = dt.strftime('%A %d %B %Y')
st3 = dt.strftime('%j')
st4 = dt.strftime('%U')
st5 = dt.strftime('%W')
print(dt)
print('Date in DD/MM/YYYY format:',st1)
print('Full date:',st2)
print('Day of the year:',st3)
print('Week of the year where Sunday is the first day of the week):',st4)
print('Week of the year where Monday is the first day of the week):',st5)

Output

2022-08-15
Date in DD/MM/YYYY format: 15/08/2022
Full date: Monday 15 August 2022
Day of the year: 227
Week of the year where Sunday is the first day of the week): 33
Week of the year where Monday is the first day of the week): 33

Time Class of DateTime Module

The time class of the datetime module is used to create a time object that represents the local time in the 24-hour format. The essential methods and attributes of the time class are:

  • time()
  • hour, minute, second, microsecond
  • isoformat()
  • fromisoformat()
  • strftime()

Let's see the use of the above methods and attributes of the time class with examples.

Create Time Object From Valid Integers

We can create a time object from valid integers using the time() constructor of the time class. The time() constructor takes four optional arguments: hour, minute, second, and microsecond.

  • Valid Hour: hour >= 0 and hour < 24
  • Valid Minute: minute >= 0 and minute < 60
  • Valid Second: second >= 0 and second < 60
  • Valid Microsecond: microsecond >= 0 and microsecond < 1000000

Let's create six different time objects using the time() constructor having a different valid integer for an hour, minute, second and microsecond.

Example

from datetime import time

tm1 = time(hour=10, minute=38, second=20, microsecond=1530)
tm2 = time(hour=8)
tm3 = time(hour=5, minute=22)
tm4 = time(hour=15, minute=43, second=50)
tm5 = time(minute=55, second=44)
tm6 = time(second=18)
print(tm1)
print(tm2)
print(tm3)
print(tm4)
print(tm5)
print(tm6)

Output

10:38:20.001530
08:00:00
05:22:00
15:43:50
00:55:44
00:00:18

Get Hour, Minute, Second and Microsecond From Time Object

We can get the hour, minute, second and microsecond from a time object by calling the hour, minute, second, and microsecond attributes of the time class.

Example

from datetime import time

tm = time(hour=13, minute=20, second=30, microsecond=486)
print(tm)
print('Hour:',tm.hour)
print('Minute:',tm.minute)
print('Second:',tm.second)
print('Microsecond:',tm.microsecond)

Output

13:20:30.000486
Hour: 13
Minute: 20
Second: 30
Microsecond: 486

Convert Time into String

We can convert a time into a string by calling the isoformat() method of the time class.

Example

from datetime import time

tm = time(hour=13, minute=20, second=30, microsecond=486)
st = tm.isoformat()
print(tm)

Output

13:20:30.000486

Convert String Representation of Time into Time Object

We can convert a time from a string format HH:MM:SS.MS into a time object by calling the fromisoformat() method of the time class.

Example

from datetime import time

st = '15:35:46.001549'
tm = time.fromisoformat(st)
print(tm)
print('Hour:',tm.hour)
print('Minute:',tm.minute)
print('Second:',tm.second)
print('Microsecond:',tm.microsecond)

Output

15:35:46.001549
Hour: 15
Minute: 35
Second: 46
Microsecond: 1549

Format Time

We can format a time using the strftime() method of the time class that returns the string representation of the formatted time.

Below is the list of format codes used for formatting the time object.

Format Code Meaning Example
%H 24 hour format with leading zero. 05, 12, 13 ,15...
%I 12 hour format with leading zero. 07, 08, 11...
%p AM or PM format AM, PM
%M Minute with leading zero. 05, 10, 20, 35...
%S Second with leading zero. 05, 10, 20, 35...
%f Microsecond with leading zero. 000001, 000754, 003984...
%y Year short format 20, 21, 22...
%Z Time zone name. (empty), UTC, EST, CST

Example

from datetime import time

tm = time(hour=15, minute=43, second=30, microsecond=5897)
st1 = tm.strftime('%H:%M:%S')
st2 = tm.strftime('%I:%M:%S %p')
st3 = tm.strftime('%I:%M:%S %f %p')
print(tm)
print('Time in 24 hour format:',st1)
print('Time in 12 hour format:',st2)
print('Time with microsecond:',st3)

Output

15:43:30.005897
Time in 24 hour format: 15:43:30
Time in 12 hour format: 03:43:30 PM
Time with microsecond: 03:43:30 005897 PM

DateTime Class of DateTime Module

The datetime class of the datetime module is used to create a datetime object representing the date and time in the 24-hour format. The essential methods and attributes of the datetime class are:

  • now()
  • strftime()
  • day, month, year, hour, minute, second, microsecond
  • datetime()
  • isoformat()
  • fromisoformat()
  • strptime()
  • isoweekday()
  • isocalendar()

Let's see the use of the above methods and attributes of the datetime class with examples.

Get Current Date and Time

We can get the current date and time by calling the now() method of the datetime class.

Example

from datetime import datetime

dt = datetime.now()
print('Current Date (YYYY-MM-DD format) and Time (24h format)=',dt)
print('Current Date (DD-MM-YYYY format) and Time (12h format)=',dt.strftime('%d-%m-%Y %I:%M:%S %p'))
print('Only Current Date (YYYY-MM-DD format)=',dt.strftime('%Y-%m-%d'))
print('Only Current Date (DD-MM-YYYY format)=',dt.strftime('%d-%m-%Y'))
print('Only Current Time (24h format)=',dt.strftime('%H:%M:%S'))
print('Only Current Time (12h format)=',dt.strftime('%I:%M:%S %p'))

Output

Current Date (YYYY-MM-DD format) and Time (24h format)= 2022-08-04 17:26:24.997591
Current Date (DD-MM-YYYY format) and Time (12h format)= 04-08-2022 05:26:24 PM
Only Current Date (YYYY-MM-DD format)= 2022-08-04
Only Current Date (DD-MM-YYYY format)= 04-08-2022
Only Current Time (24h format)= 17:26:24
Only Current Time (12h format)= 05:26:24 PM

Note: We can use the strftime() method of the datetime class to format the datetime object using the date and time format codes given in the date and time format codes tables.

Get Day, Month, Year, Hour, Minute, Second and Microsecond From DateTime Object

We can get the day, month, year, hour, minute, second and microsecond from a datetime object by calling the day, month, year, hour, minute, second, and microsecond attributes of the datetime class.

Example

from datetime import datetime

dt = datetime.now()
print(dt)
print('Day:',dt.day)
print('Month:',dt.month)
print('Year:',dt.year)
print('Hour:',dt.hour)
print('Minute:',dt.minute)
print('Second:',dt.second)
print('Microsecond:',dt.microsecond)

Output

2022-08-04 16:12:34.766442
Day: 4
Month: 8
Year: 2022
Hour: 16
Minute: 12
Second: 34
Microsecond: 766442

Create DateTime Object From Valid Integers

We can create a datetime object from valid integers using the datetime() constructor of the datetime class. The datetime() constructor takes seven arguments: day, month, year, hour, minute, second, and microsecond. Among these arguments, the first three are compulsory, while the rest are optional.

Example

from datetime import datetime

dt = datetime(day=18, month=9, year=2022, hour=10, minute=38, second=20, microsecond=1530)
print(dt)

Output

2022-09-18 10:38:20.001530

Convert DateTime into String

We can convert a datetime into a string by calling the isoformat() method of the datetime class.

Example

from datetime import datetime

dt = datetime.now()
st = dt.isoformat()
print(st)

Output

2022-08-04T17:44:28.643313

Convert String Representation of DateTime into DateTime Object

We can convert a datetime from a string format YYYY-MM-DD HH:MM:SS.MS into a datetime object by calling the fromisoformat() method of the datetime class.

Example

from datetime import datetime

st = '2022-08-02 15:24:36.005698'
dt = datetime.fromisoformat(st)
print('Day =',dt.day)
print('Month =',dt.month)
print('Year =',dt.year)
print('Hour:',dt.hour)
print('Minute:',dt.minute)
print('Second:',dt.second)
print('Microsecond:',dt.microsecond)

Output

Day = 2
Month = 8
Year = 2022
Hour: 15
Minute: 24
Second: 36
Microsecond: 5698

Convert a Formatted String Representation of DateTime into DateTime Object

We can convert a formatted string representation of datetime into a datetime object by calling the strptime() method of the datetime class. The strptime() method takes two arguments: the datetime formatted string and the formatted codes of the formatted datetime string.

Example

from datetime import datetime

st1 = '18-06-2022 15:24:36.005698'
st1_format = '%d-%m-%Y %H:%M:%S.%f'
st2 = '05/12/2021 05:15 PM'
st2_format = '%m/%d/%Y %I:%M %p'
dt1 = datetime.strptime(st1, st1_format)
dt2 = datetime.strptime(st2, st2_format)
print(dt1)
print(dt2)

Output

2022-06-18 15:24:36.005698
2021-05-12 17:15:00

Get Weekday as Integer From DateTime Object

We can get the weekday as an integer from a datetime by calling the isoweekday() method of the datetime class that returns the weekday as an integer where Monday represents 1 and Sunday represents 7.

Example

from datetime import datetime

day = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
st = '2022-05-18 15:24:36.005698'
dt = datetime.fromisoformat(st)
wd = dt.isoweekday()
print("Weekday on 18th May 2022 = %d %s" %(wd, day[wd-1]))

Output

Weekday on 18th May 2022 = 3 Wednesday

Get Year, Week, Weekday From DateTime Object

We can get the year, week, and weekday from a datetime by calling the isocalendar() method of the datetime class that returns a tuple containing year, week, and weekday.

Example

from datetime import datetime

st = '2022-05-28'
dt = datetime.fromisoformat(st)
x = dt.isocalendar()
print(x)
print('Year =', x[0])
print('Week =', x[1])
print('Weekday =', x[2])

Output

(2022, 21, 6)
Year = 2022
Week = 21
Weekday = 6

TimeDelta Class of DateTime Module

The timedelta class of the datetime module is used to find the difference between two dates, times, and datetime objects. It is also used to find the future and previous date and time by adding a timedelta period to the existing date and time objects. The essential methods and attributes of the timedelta class are:

  • days, seconds, microseconds
  • timedelta()

Let's see the use of the above methods and attributes of the datetime class with examples.

Difference Between Two Dates

The program below demonstrates how to find the difference between two dates in the form of days and weeks.

Example

from datetime import datetime

s1 = '26-03-2021'
s2 = '05-07-2022'
dt_format = '%d-%m-%Y'
dt1 = datetime.strptime(s1, dt_format)
dt2 = datetime.strptime(s2, dt_format)
dt3 = dt2-dt1
print(dt1.strftime(dt_format))
print(dt2.strftime(dt_format))
print('Diffetence in days between two dates = %d Days' %(dt3.days))
print('Diffetence in weeks between two dates = %d Weeks' %(dt3.days//7))

Output

26-03-2021
05-07-2022
Diffetence in days between two dates = 466 Days
Diffetence in weeks between two dates = 66 Weeks

In the above program, dt3 becomes a timedelta object.

Difference Between Two Times

The program below demonstrates how to find the difference between two dates in the form of days and weeks.

Example

from datetime import datetime

s1 = '03:23:47 PM'
s2 = '08:20:33 AM'
tm_format = '%I:%M:%S %p'  # 12h format
tm1 = datetime.strptime(s1, tm_format)
tm2 = datetime.strptime(s2, tm_format)
td = tm1-tm2
print(tm1.strftime(tm_format))
print(tm2.strftime(tm_format))
print('Diffetence between two times = %s' %(td))

hours = td.seconds // 3600
minutes = (td.seconds % 3600) // 60
seconds = (td.seconds % 3600) % 60

print('Hours= %d' %(hours))
print('Minutes= %d' %(minutes))
print('Seconds= %d' %(seconds))
print('Total Seconds= %d' %(td.seconds))

Output

03:23:47 PM
08:20:33 AM
Diffetence between two times = 7:03:14
Hours= 7
Minutes= 3
Seconds= 14
Total Seconds= 25394

In the above program, td becomes a timedelta object. To convert total seconds in hours we have divided the total seconds by 3600 (1 hour = 3600 seconds).

Get Previous and Future Dates

The program below demonstrates how to find the previous and future dates from an existing date using a timedelta object. The timedelta() constructor takes seven optional arguments: days, seconds, microseconds, milliseconds, minutes, hours, and weeks.

Example

from datetime import date, timedelta

dt = date(day=18, month=9, year=2022)
period = timedelta(days=10)
previous_date = dt-period
future_date = dt+period
print('Existing Date: %s' %(dt))
print('Previous Date: %s' %(previous_date))
print('Future Date: %s' %(future_date))

Output

Existing Date: 2022-09-18
Previous Date: 2022-09-08
Future Date: 2022-09-28

In the above program, we have subtracted and added 10 days using a timedelta object to an existing date to find the previous and future dates.

Get Previous and Future Dates and Times

The program below demonstrates how to find the previous and future dates and times from an existing date and time using a timedelta object.

Example

from datetime import datetime, timedelta

dt = datetime(day=15, month=6, year=2022, hour=15, minute=22, second=49)
period = timedelta(days=5, hours=5, minutes=35, seconds=52)
previous_datetime = dt-period
future_datetime = dt+period
print('Existing Date and Time: %s' %(dt))
print('Previous Date and Time: %s' %(previous_datetime))
print('Future Date and Time: %s' %(future_datetime))

Output

Existing Date and Time: 2022-06-15 15:22:49
Previous Date and Time: 2022-06-10 09:46:57
Future Date and Time: 2022-06-20 20:58:41