Python Datetime Module Tutorial

The Python Datetime Module will enable you to work with date and time in Python. This module gives you date, time, datetime, and timedelta classes that help you to create date and time objects. Each class has some attributes and methods that will help you to manipulate and represent date and time.

How To Represent Dates Using Python Datetime Module

To represent a date you have to create a Date Object like this : 

import datetime

date=datetime.date(2022,9,15)

Date Class Attributes

dayIt returns the day number of the given date.
monthThis will return the month number of the given date.
yearIt returns the year of the given date.
minThis will help you to get the earliest representable date.
maxWith this, you can get the latest representable date.

Example :

import datetime

date=datetime.date(2022,9,15)

print(date)
print("----------------")
print("day =",date.day)
print("month =",date.month)
print("year =",date.year)

print("----------------")
print("Latest Date =",date.max)
print("Earliest Date =",date.min)

Output :

2022-09-15
----------------
day = 15
month = 9
year = 2022
----------------
Latest Date = 9999-12-31
Earliest Date = 0001-01-01

Date Class Methods

today() = With the help of this function, you can get the current local date.

Example :

import datetime

date=datetime.date.today()
print(date)

Output :

2023-04-26

ctime() = This function will represent the date in string format.

Example :

import datetime

date=datetime.date.today()
print(date.ctime())

Output :

Wed Apr 26 00:00:00 2023

weekday() = It will return you an integer that represents the day of the week. You will get “0” if the day is Monday, “1” for Tuesday, and “6” for Sunday.

isoweekday() = This function works like the weekday() function but it returns “1” for Monday and “7” for Sunday.

Example :

import datetime

date=datetime.date.today()

print("Weekday =",date.weekday())
print("ISO Weekday =",date.isoweekday())

Output :

Weekday = 2
ISO Weekday = 3

isocalender() = This function returns you a tuple of 3 numbers. The first number will represent the ISO year, the second number represents the ISO week number of the year, and the third number will represent the ISO day of the week.

Example :

import datetime

date=datetime.date.today()
print(date.isocalendar())

Output :

(2023, 17, 3)

isoformat() = It will represent the date in the ISO format – “YYYY-MM-DD”.

Example :

import datetime

date=datetime.date.today()
print(date.isoformat())

Output :

2023-04-26

replace() = This function can help you to replace the day number, month, year, or full date. See the below example to get a better understanding.

Example :

import datetime

date=datetime.date(2022,9,15)

print(date.replace(year=2020))
print(date.replace(day=20))
print(date.replace(month=2))
print(date.replace(year=2024,month=12,day=31))

Output :

2020-09-15
2022-09-20
2022-02-15
2024-12-31

timetuple() = It returns a time.struct_time object that contains the day of the month, year, month of the year, and day of the year. The object also contains hour, minute, and second but the value will be 0.

Example :

import datetime

date=datetime.date.today()

print(date)
print("----------------------------")

print(date.timetuple())
print("----------------------------")

print("day number of month =",date.timetuple().tm_mday)
print("Year number =",date.timetuple().tm_year)
print("day number of week =",date.timetuple().tm_wday)
print("day number of year =",date.timetuple().tm_yday)
print("month number of year =",date.timetuple().tm_mon)

Output :

2023-04-26
----------------------------
time.struct_time(tm_year=2023, tm_mon=4, tm_mday=26, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=116, tm_isdst=-1)
----------------------------
day number of month = 26
Year number = 2023
day number of week = 2
day number of year = 116
month number of year = 4

How To Represent Time Using Python Datetime Module

To represent time you have to create a Time Object like this : 

import datetime

time=datetime.time(hour=22,minute=42,second=25,microsecond=66)

Time Class Attributes

minWith this, you will get the earliest representable time.
maxIt returns you the latest representable time.
hourBy using this, you will get hours.
minuteIt returns minutes.
secondIt returns seconds.
microsecondThis will give you microseconds.

Example :

import datetime

time=datetime.time(hour=22,minute=42,second=25,microsecond=66)

print(time)
print("-------------------")

print("Earliest Representable Time =",time.min)
print("Latest Representable Time =",time.max)
print("-------------------")

print("Hours =",time.hour)
print("Minutes =",time.minute)
print("Seconds =",time.second)
print("Microseconds =",time.microsecond)

Output :

22:42:25.000066
-------------------
Earliest Representable Time = 00:00:00
Latest Representable Time = 23:59:59.999999
-------------------
Hours = 22
Minutes = 42
Seconds = 25
Microseconds = 66

Time Class Methods

replace() = With the help of this function, you can replace hours, minutes, seconds, milliseconds, or an overall time.

Example :

import datetime

time=datetime.time(hour=22,minute=42,second=25,microsecond=66)
print(time.replace(hour=18,minute=20)) 

Output :

18:20:25.000066

How To Represent Both Date And Time Together

To represent both date and time together you have to create a Datetime Object like this : 

import datetime

dt=datetime.datetime(2022,8,22,16,45,20,600)

With the Datetime object, you can use all the attributes of the Date Class and Time Class

Example :

import datetime

dt=datetime.datetime(2022,8,22,16,45,20,600)
print(dt)

print("------------------")
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)

print("------------------")
print("Earliest Representable Date And Time =", dt.min)
print("Earliest Representable Date And Time =", dt.max)

Output :

2022-08-22 16:45:20.000600
------------------
Day = 22
Month = 8
Year = 2022
Hour = 16
Minute = 45
Second = 20
Microsecond = 600
------------------
Earliest Representable Date And Time = 0001-01-01 00:00:00
Earliest Representable Date And Time = 9999-12-31 23:59:59.999999

Datetime Class Methods

date() = This function will return a Date Object with the same date as the given Datetime Object.

time() = It returns a Time Object with the same time as the given Datetime Object.

Example :

import datetime

dt=datetime.datetime(2022,8,22,16,45,20,600)

print(dt)
print("------------------")

print("Date =", dt.date())
print("Time =", dt.time())

Output :

2022-08-22 16:45:20.000600
------------------
Date = 2022-08-22
Time = 16:45:20.000600

replace() = With the help of this function, you can replace the values of any or all of the attributes of the Datetime Object.

Example :

import datetime

dt=datetime.datetime(2022,8,22,16,45,20,600)

print(dt)
print("------------------")
print(dt.replace(2024,9,3,12,30,45,20))

Output :

2022-08-22 16:45:20.000600
------------------
2024-09-03 12:30:45.000020

now() = This function will return you a Datetime Object with the current local date and time.

Example :

import datetime

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

Output :

2023-04-26 01:40:32.915416

isoformat(sep) = It will return you a string that represents the date and time in the ISO format. You can pass a separator as an argument to this function which will separate the date and time.

Example :

import datetime

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

print("------------------")
print(dt.isoformat("/"))

Output :

2023-04-26 01:47:27.193869
------------------
2023-04-26/01:47:27.193869

combine(date, time) = This function returns a Datetime Object with the date and time of the given date and time object.

Example :

import datetime

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

print("------------------")
print(dt.combine(date=datetime.date(2021,8,28),time=datetime.time(8,56,22)))

Output :

2023-04-26 01:48:45.298612
------------------
2021-08-28 08:56:22

Other methods of Date and Time Objects that you can use with the Datetime Object.

  • weekday()
  • ctime()
  • isocalender()
  • isoweekday()
  • today()

Example :

import datetime

dt=datetime.datetime.today()

print(dt)
print("------------------")

print("Weekday =", dt.weekday())
print("ISO Weekday =", dt.isoweekday())

print("Date and Time in String Format =", dt.ctime())
print("ISO Calender =", dt.isocalendar())

Output :

2023-04-26 02:03:56.312407
------------------
Weekday = 2
ISO Weekday = 3
Date and Time in String Format = Wed Apr 26 02:03:56 2023
ISO Calender = (2023, 17, 3)

How To Calculate Duration Between Two Dates And Times

The Timedelta Object can help you to represent the duration between dates and times. With the help of Timedelta class, you can create a Timedelta Object like this :  

import datetime

timedelta=datetime.timedelta(weeks=3,days=7,hours=24,minutes=30,seconds=45,milliseconds=23,microseconds=88)

Timedelta Class Attributes

min It returns you the most negative Timedelta Object.
maxThis will return you the most positive Timedelta Object.

Example :

import datetime

timedelta=datetime.timedelta(weeks=3,days=7,hours=24,minutes=30,seconds=45,milliseconds=23,microseconds=88)

print(timedelta)

print("Most Positive =", timedelta.max)
print("Most Negative =", timedelta.min)

Output :

29 days, 0:30:45.023088
Most Positive = 999999999 days, 23:59:59.999999
Most Negative = -999999999 days, 0:00:00

Timedelta Class Methods

total_seconds() = This function will return you the total number of seconds contained in the given time duration.

Example :

import datetime

timedelta=datetime.timedelta(weeks=3,days=7,hours=24,minutes=30,seconds=45,milliseconds=23,microseconds=88)

print(timedelta.total_seconds())

Output :

2507445.023088

You can also use the mathematical operators to do the calculations with timedelta.

Example :

import datetime

timedelta=datetime.timedelta(weeks=3,days=7,hours=24,minutes=30,seconds=45,milliseconds=23,microseconds=88)

timedeltadays=datetime.timedelta(days=7)
timedeltahours=datetime.timedelta(hours=20)

print(timedelta-timedeltadays)
print("-------------------")

print(timedelta+timedeltahours)
print("-------------------")

print(timedelta*2)
print("-------------------")

print(timedelta/2)

Output :

22 days, 0:30:45.023088
-------------------
29 days, 20:30:45.023088
-------------------
58 days, 1:01:30.046176
-------------------
14 days, 12:15:22.511544

Other Important Methods Of Python Datetime Module

strftime(format) = With the help of this method, you can create a special string format that represents a date and time. You can create a format using some special format codes.

Following Are Some Important Format Codes:- 

CodesMeaningExample
%aLocal abbreviation of WeekdaysSun, Mon
%ALocal full name of WeekdaysSunday, Monday
%wWeekdays as a number0 for Sunday, 6 for Saturday
%dDay number of the month01, 02, ….. 31
%bAbbreviation name of MonthJan, Feb, …., Dec
%BFull Name of MonthJanuary, February, ….. December
%mMonth Number 01, 02, ……, 12
%yLast Two Digit of Year01, 02, ….., 98, 99
%YFull Year Number0001, 0002, …., 9998, 9999
%HHours Number of the 24-hour clock01, 02, ……, 12
%IHours Number of the 12-hour clock00, 01, …….., 23
%MMinutes Number00, 01, ………, 59
%SSeconds Number00, 01, ………, 59
%jDay Number of the Year001, 002, ….., 366
%UWeek Number of the Year (Sunday is the first day of the Week)01, 02, ….., 53
%WWeek Number of the Year (Monday is the first day of the Week)01, 02, ….., 53

Example :

import datetime

dt=datetime.datetime.today()

print(dt.strftime("%a %w %B"))
print(dt.strftime("%A %d %b %H:%M %p -- %j %U"))
print(dt.strftime("%A %d %b %H:%M %p -- %j %u"))
print(dt.strftime("%c"))

print("-------------------------------")
print(dt.time().strftime("%H:%M:%S %p"))
print(dt.time().strftime("%X"))

print("-------------------------------")
print(dt.date().strftime("%A, %d %B %Y"))
print(dt.date().strftime("%x"))

Output :

Wed 3 April
Wednesday 26 Apr 01:57 AM -- 116 17
Wednesday 26 Apr 01:57 AM -- 116 3
Wed Apr 26 01:57:42 2023
-------------------------------
01:57:42 AM
01:57:42
-------------------------------
Wednesday, 26 April 2023
04/26/23

strptime(date_string, format) = This function works opposite of the strftime(), it will convert your given string format into a Datetime object. You have to pass two arguments to this function – the first is date_string and the second is the format.

Example :

import datetime

dt=datetime.datetime.today()

print(dt.strptime("16 november 2022","%d %B %Y"))
print("----------------------")

print(dt.strptime("22 Nov 18","%y %b %d"))
print("----------------------")

print(dt.strptime("Apr 24 2024 18 50 25","%b %d %Y %H %M %S"))
print("----------------------")

print(dt.strptime("154 2024 7 50 25","%j %Y %I %M %S"))
print("----------------------")

print(dt.strptime("7/16/22","%x"))

Output :

2022-11-16 00:00:00
----------------------
2022-11-18 00:00:00
----------------------
2024-04-24 18:50:25
----------------------
2024-06-02 07:50:25
----------------------
2022-07-16 00:00:00

Other General Modules

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *