Python provides an inbuilt module ‘datetime‘ to work with date and time. We have to import the ‘datetime’ module in order to work with it. Let us start working with simpler programs to understand the usage of the Python datetime.
Table of Contents
Attributes of Python datetime module:
We can get the list of attributes of a Python datetime module using dir().
import datetime print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__packa ge__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
The most commonly used classes of datetime module are:
- date class
- time class
- datetime class
- timedelta class
Python datetime class:
Get the current date and time:
With ‘datetime’ class we can get the current date and time. The class ‘datetime’ has a method ‘now’. Calling the now() method returns the current local date and time.
import datetime print(datetime.datetime.now())
2020-09-08 15:55:17.833232
Instantiate datetime class:
We can instantiate the datetime class. The constructor takes the below arguments:
datetime.datetime(year, month, day, hour, minute, second, microsecond)
Whereas year, month, and day are the mandatory parameters. The remaining parameters are optional.
import datetime date_time1=datetime.datetime(2020, 2, 29) date_time2=datetime.datetime(2020, 2, 29, 23, 59, 59, 345678) print(date_time1) print(date_time2)
2020-02-29 00:00:00 2020-02-29 23:59:59.345678
Get attributes of datetime class:
We can print the attributes of the datetime class like an hour, month, second, timestamp, etc., using its object.
import datetime date_time=datetime.datetime(2020, 2, 29, 23, 59, 59, 345678) print(date_time.month) print(date_time.microsecond) print(date_time.timestamp())
2 345678 1583000999.345678
date class:
Get the current date:
We can get the current date alone from the ‘date’ class in two ways:
Using today():
The class ‘date’ has a method ‘today’. When we call the today() method, it returns the current local date alone.
import datetime print(datetime.date.today())
2020-09-08
Using fromtimestamp():
A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC. The fromtimestamp() method converts the timestamp to date.
import datetime print(datetime.date.fromtimestamp(1599571319))
2020-09-08
Instantiate date class:
We can also instantiate the objects of a date class. The constructor of a date class takes 3 mandatory arguments: (year, month, day).
import datetime print(datetime.date(2020, 2, 29))
2020-02-29
Get year, month, and day of a date:
We can also get the year, month, and day of a particular date individually from the date class.
import datetime today=datetime.date.today() print(today.year) print(today.month) print(today.day)
2020 9 8
time class:
Get current time:
Unfortunately, we cannot get the current time from the time class as we get the date from the date class. We can get the current time from the now() method of the datetime class as below:
import datetime print(datetime.datetime.now().time())
20:30:49.929395
Instantiate time class:
Like date class, we can also instantiate the time class.
import datetime print(datetime.time())
00:00:00
The constructor the time class takes the below arguments:
datetime.time(hour, minute, second, microsecond)
It is not mandatory that we have to pass all the arguments.
import datetime print(datetime.time(11)) print(datetime.time(11, 59)) print(datetime.time(11, 59, 59)) print(datetime.time(11, 59, 59, 345678))
11:00:00 11:59:00 11:59:59 11:59:59.345678
Get hour, minute, second, microsecond:
We can print the hour, minute, second, and microsecond attributes individually using the time object.
import datetime time_object=datetime.time(11, 59, 59, 345678) print(time_object.hour) print(time_object.minute) print(time_object.second) print(time_object.microsecond)
11 59 59 345678
timedelta class:
The timedelta is nothing but the difference between two dates or two times.
import datetime date1=datetime.date(2019,2,28) date2=datetime.date(2020,2,29) time1=datetime.datetime(2019,2,28,7,55,59,234567) time2=datetime.datetime(2020,2,29,6,59,58,345678) timedelta1=date2-date1 timedelta2=time2-time1 print(timedelta1) print(timedelta2) print(type(timedelta1)) print(type(timedelta2))
366 days, 0:00:00 365 days, 23:03:59.111111 <class 'datetime.timedelta'> <class 'datetime.timedelta'>
If you notice the type of difference between the date and datetime objects, it’s timedelta.
Instantiate timedelta class:
Like the other classes, we can also instantiate the timedelta class.
import datetime timedelta1=datetime.timedelta(weeks=2, seconds=59) timedelta2=datetime.timedelta(days=2, seconds=56) timedelta3=timedelta1-timedelta2 print(timedelta3) print(type(timedelta3))
12 days, 0:00:03 <class 'datetime.timedelta'>
Negative timedelta objects:
We can make use of abs() to print the negative timedelta object.
import datetime timedelta1=datetime.timedelta(weeks=2, seconds=59) timedelta2=datetime.timedelta(days=2, seconds=56) timedelta3=timedelta2-timedelta1 print(timedelta3) print(abs(timedelta3))
-13 days, 23:59:57 12 days, 0:00:03
We can not only find the difference between two timedelta objects but also the sum with the ‘+’ operator. Also, we can multiply and divide the timedelta objects by integers and floats.
Python format datetime:
In some scenario, you might want to represent the date and time in a format which you want. For example, for dates instead of using ‘yyyy-mm-dd’ format, you want ‘dd/mm/yyyy’ format.
Python provides the below two methods for this purpose.
- strftime()-converts datetime object to string
- strptime()-converts the string object back to datetime
strftime():
The method strftime() is defined under the classes datetime, date, and time. Hence it converts the datetime, time, and date objects to a string.
import datetime now=datetime.datetime.now() t=now.strftime('%H:%M:%S') str1=now.strftime('%d/%m/%Y, %H:%M:%S') str2=now.strftime('%m/%d/%Y, %H:%M:%S') print(now) print(t) print(str1) print(str2) print(type(t),type(str1),type(str2))
2020-09-09 17:34:27.000451 17:34:27 09/09/2020, 17:34:27 09/09/2020, 17:34:27 <class 'str'> <class 'str'> <class 'str'>
Here %H, %M, %S, %Y, %m, %s are the format codes. The below is the list of format codes, what they represent and the value it takes.
%H – Hour(00 to 23)
%M – Minutes(00 to 59)
%S – Seconds(00 to 59)
%Y – Year(0000 to 9999)
%m – month(00 to 12)
%d – day(00 to 31)
strptime():
strptime() creates a datetime object from the given string.
import datetime str='29 March, 2020' d=datetime.datetime.strptime(str, '%d %B, %Y') print(d) print(type(d))
2020-03-29 00:00:00 <class 'datetime.datetime'>
Here the format code %B represents the full name of the month.