Python - Datetime

Usually working with date, time and timezone is complicated. But Python has separate and standard libraries to work with date and times.
Python has special module datetime to manipulate the dates and times.

Datetime module has common types - date, datetime, time and timedelta.

datetime.date class

A date object represent the date with year, month, and day. We can initiate the date object using date Class.

Example:

import datetime

specific_date = datetime.date(2022,1,28)
print(specific_date)

Output

2022-01-28

You can also import date class from datetime module.

Example:

from datetime import date
    
specific_date= date(2022,1,28)
print(spcific_date)

Output

2022-01-28

As you can see, date class used directly to create the date object.

datetime.time class

A time object represent the time with hour, minute and seconds (optionally milliseconds). We can initiate the time object using time Class.

Example 1:

import datetime

specific_time = datetime.time(9,50,30)
print(specific_time)

Output

09:50:30

Example 2:

import datetime

time_with_microseconds = datetime.time(9,50,30,100000)
print(time_with_microseconds)

Output

09:50:30.100000

Example 3:

import datetime

t = datetime.time(9,50,30,100000)
print(t)
print("hour -", t.hour)
print("minutes - ", t.minute)
print("seconds - ", t.minute)
print("microseconds - ",t.microsecond)

Output

hour - 9
minutes -  50
seconds -  30
microseconds -  100000
datetime.datetime class

A datetime module has the datetime class which contains both date and time details. We can initiate the datetime object using datetime Class.

Example:

import datetime

specific_date = datetime.datetime(2022,1,27)
print(specific_date)

specific_date_with_time = datetime.datetime(2022,1,27,11,50,55,100000)
print(specific_date_with_time) 

Output

2022-01-27 00:00:00
2022-01-27 11:50:55.100000
datetime.timedelta class

A timedelta object creates when you find the time difference between two dates or times. Also, we can initiate the time delta object using timedelta Class.

Example:

from datetime import date, date-time

time1 = date(year=2022,month=1,day=27)
time2 = date(year=2022,month=1,day=12)
time3 = time1 - time2
print(“time3 - ”,time3)

time4 = datetime(year=2022, month=1, day=27,hour=11,minute=50,second=55,microsecond=234567)
time5 = datetime(year=2022,month=1,day=12,hour=11,minute=25,second=50, microsecond=234567)
time6= time4 - time5
print(“time6 - ”,time6)

print("Type of time3 - ",type(time3))
print("Type of time6 - ",type(time6))

Output

time3 -  15 days, 0:00:00
time6 -  15 days, 0:25:05
Type of time3 -  < class 'datetime.timedelta' >
Type of time6 -  < class 'datetime.timedelta' >

As you can see, the types of time3 and time6 are timedelta class



Related Tutorials