In this post, we’re going to dive into the Python datetime module and explore how we can effectively implement date and time data into our Python code.
Regardless of what area of Python programming you’re pursuing, this is a must-know module with an endless amount of uses and tons of professional career applications.
Let’s get started!
Prerequisites : The reader is expected to have a working knowledge of the Python programing language.
About Python Datetime
The Python datetime module contains various classes to represent and manipulate dates and times. The key classes in datetime are date, time, datetime, timedelta, tzinfo, timezone. We will look briefly at the date, time, and timedelta objects and in more detail at the datetime objects. Timezone is not covered in this article.
Aware Vs Naive Objects
Date and Time objects that contain timezone and daylight saving time (DST) info are called aware objects. An aware object represents a moment in time that is not open to interpretation and can locate itself relative to other aware objects. Naive objects are simpler, and represent either UTC or local time etc. and cannot locate themselves relative to other aware objects.
date objects are naive. datetime and time objects may be naive or aware.
Creating date objects
A date object represents a date. The constructor for date objects is date(year, month, day). A date can also be created from an existing date by using the replace method to replace the year/month/date. We can also set the day of the week as well.
# date constructor >>> d = date (1999, 5, 26) # methods to get data >>> d.day 26 >>> d.month 5 >>> d.year 1999 # Monday = 0, Sunday = 6 >>> d.weekday() 2 # Monday = 1, Sunday = 7 >>>> d.isoweekday() 3 >>> d.replace (month=11) datetime.date(1999, 11, 26)
Important date class methods
The following methods are defined on the date class and provide information about the range of dates supported by the date class.
# the earliest representable date >>> print (date.min) 0001-01-01 # the latest representable date >>> print (date.max) 9999-12-31 # the smallest possible difference between 2 non-equal date objects. >>> print (date.resolution) 1 day, 0:00:00
The date object can be formatted in different ways using different methods of the date class. strftime is a powerful formatting method that supports several formats. We will look at it in detail in a subsequent section.
>>> d = date (1999, 5, 26) >>> d.isoformat() '1999-05-26' >>> d.ctime() 'Wed May 26 00:00:00 1999' >>> d.strftime('%d%m%y') '260599'
strftime for the date object
The general syntax of strftime is as follows:
strftime is an instance method on the datetime, date, time objects. It converts a date object into a formatted string. It supports numerous formatting strings described in detail in the Python Documentation. In this section, we look at a few examples of strftime formatting in the context of the date object.
The formatting codes for hour, minute, seconds, microseconds should not be used here as they don’t apply to date objects. If used, they are substituted with 0.
>>> d.strftime('%A %B %Y') 'Wednesday May 1999' >>> d.strftime('%a %b %y') 'Wed May 99' # %j = day of the year >>> d.strftime('%a %b %y %j') 'Wed May 99 146' # %U = week of the year (Sunday = 1) >>> d.strftime('%j %U') '146 21'
A time object represents a time of day, independent of day. It can be adjusted using a timezone (tzinfo) object. Arithmetic is not supported on time objects.
Creating time objects
A time object can be created by using the time constructor, from an existing time object by using the replace method (to replace the hour/minute/second/microsecond) or from an iso formatted string.
The constructor for the time object is as follows.
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0
from datetime import time >>> t = time(12, 25, 9) >>> t.hour 12 >>> t.second 9 >>> t.minute 25 >>> t.microsecond 0 >>> t.isoformat() '12:25:09' >>> t.strftime('%H:%M:%S') '12:25:09' # New date from existing date by replacing minute >>> t2 = t.replace(minute=44) >>> t2.isoformat() '12:44:09' # new time from isoformatted string >>> t3 = time.fromisoformat('14:45:59') >>> t3 datetime.time(14, 45, 59) >>> t3.isoformat() '14:45:59'
strftime for the time object
strftime is an instance method on the datetime, date, time objects. It converts a time object into a formatted string. It supports numerous formatting strings described in detail in the Python Documentation. In this section, we look at a few examples of strftime formatting in the context of the time object.
The formatting strings for year, month, and day should not be used here as they don’t apply to time objects. If used,
1900 is substituted for the year, and
1 for the month and day.
>>> t = time(12, 25, 9) # 24-hour clock >>> t.strftime('%H:%M:%S') '14:45:59' # 12-hour clock >>> t.strftime('%I:%M:%S %p') '02:45:59 PM' # 1 substituted for month, day, 1900 for year >>> t.strftime('%c') 'Mon Jan 1 14:45:59 1900'
Important time class methods
The following methods are defined on the time class and provide information on the range of time supported by the time class.
# the earliest representable time >>> print (time.min) 00:00:00 # the latest representable time >>> print (date.max) 23:59:59.999999 # the smallest possible difference between 2 non-equal time objects. >>> print (date.resolution) 0:00:00.000001
timedelta is a time duration expressing the difference between 2 date / time / datetime objects to microsecond precision. It’s important to remember that arithmetic is not supported on time objects. Hence we have to convert time objects into datetime objects with any valid date and then compute the difference. Alternately a dummy date object can be combined with each of the time objects and the resultant datetime objects could be used to compute the difference.
# difference between dates >>> d1 = date(2000, 11, 24) >>> d2 = date(2001, 11, 24) >>> td = d2 -d1 '365 days, 0:00:00' # arithmetic between times not allowed. >>> t1 = time(12, 56, 57) >>> t2 = time(12, 57, 54) >>> str(t2 - t1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' # convert time objects into datetime objects (with the same date) # and then do the math >>> dt1 = datetime(2000, 11, 24, 12, 57, 54) >>> dt2 = datetime(2000, 11, 24, 10, 56, 53) # diff = 2 hrs, 1 minute, 1 second >>> str(dt1 - dt2) '2:01:01' # total difference in seconds >>> (dt2 - dt1).total_seconds() 2584739.0
datetime is an important object of the datetime module, containing information from a date and a time object.
Creating datetime objects
datetime objects can be created using a constructor, from iso strings, POSIX timestamps, UTC time stamps, combining date and time objects. The current date and time can also be returned using methods like now() and today(). We look at a few of these methods below. For a comprehensive treatise on creating datetime objects, see the Python documentation.
The constructor format is as follows :
# datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) # example >>> d = datetime(1999, 7, 23, 23, 56, 59) >>> d.year 1999 >>> d.month 7 >>>> d.day 23 >>> d.hour 23 >>> d.minute 56 >>> d.second 59 >>> d.isoformat() 1999-07-23T23:56:59 >>> d.timestamp() 932754419.0
datetime.now() can be used to get the current local date, time as a datetime object.
from datetime import datetime as dt # print the current local date, time now = dt.now() print (now) # yyyy-mm-dd hh:mm:ss.microseconds 2021-07-26 16:39:07.104867 # day >>> print (now.day) 26 # month >>> print (now.month) 7 >>> print (now.hour) 16 # minute >>> print (now.minute) 39 >>> iso format print (now.isoformat()) '2021-07-26T16:39:07.104867'
datetime from the ISO format
A datetime object can be created from an ISO formatted string as follows.
>>> datetime.fromisoformat('2011-11-04T00:05:23') datetime.datetime(2011, 11, 4, 0, 5, 23)
Combining date and time objects into datetime
date and time objects can be combined into a datetime object using the combine method.
>>> d = date(1999, 8,25) >>> t = time(23, 4, 55) >>> >>> dt = datetime.combine(d, t) >>> dt datetime.datetime(1999, 8, 25, 23, 4, 55)
Arithmetic with datetime objects
Datetime objects can be added or subtracted to/from timedelta objects to produce a datetime object. The example below adds and subtracts a timedelta of 30 days to the current date to produce datetime objects, 1 month later and 1 month earlier than the current date.
# today is a datetime object >>> today = datetime.now() >>> today datetime.datetime(2021, 7, 27, 15, 25, 8, 89016) # thirty_days is a timedelta object >>> thirty_days = timedelta(days=30) >>> thirty_days datetime.timedelta(days=30) >>> thirty_days + today datetime.datetime(2021, 8, 26, 15, 25, 8, 89016) >>> today - thirty_days datetime.datetime(2021, 6, 27, 15, 25, 8, 89016) >>> today.strftime("%a %x") 'Tue 07/27/21'
strftime and strptime for datetime
strftime is a method to convert a datetime object into a formatted string under the control of a format string. strptime is a datetime class method that converts a string representing date-time into a datetime object using a format string.
Examples of strftime
>>> today = datetime.now() >>> today.strftime("%d %B %Y") '27 July 2021' >>> today.strftime("%d %B %Y %H %M %S%p") '27 July 2021 15 25 08PM' >>> today.strftime("%c") 'Tue Jul 27 15:25:08 2021' >>> today.strftime("%x") '07/27/21' >>> today.strftime("%a %x") 'Tue 07/27/21'
Examples of strptime
>>> datetime.strptime('07/27/21', "%x") datetime.datetime(2021, 7, 27, 0, 0) >>> datetime.strptime('Wed 07/28/21', "%a %x") datetime.datetime(2021, 7, 28, 0, 0) >>> datetime.strptime('27 July 2021 15 25 08PM', "%d %B %Y %H %M %S%p") datetime.datetime(2021, 7, 27, 15, 25, 8)
A timestamp is a way of representing datetime objects as a UNIX epoch i.e. the number of seconds that have elapsed from Jan 1st 1970 UTC. It’s very simple to convert between a datetime object and the time stamp.
# datetime => timestamp >>> dt = datetime(2002, 7, 24, 7, 18, 22) >>> dt.timestamp() 1027475302.0 # timestamp => datetime >>> ts = dt.timestamp() >>> dt2 = datetime.fromtimestamp(ts) >>> dt2 datetime.datetime(2002, 7, 24, 7, 18, 22)
Ready to learn more about Python datetime or Python in general? Explore some of the links below!
- Python Documentation – datetime
- Pythontic.com – weekday function
- W3Schools – datetime
- Python Docs – strftime and strptime Behaviour
- Kite.com – Subtracting one datetime.time object from another using datetime.combine
- Howchoo.com – Working with datetime and timezone objects in Python.
- kdnuggets – How to use Python’s datetime.
- Zenva – Python Mini-Degree
And there we have it – you now have a greater understanding of the Python datetime module and how you can use it for whatever you might need in a Python program. As we discussed, the Python datetime module has various classes to handle dates and times. The key classes are date, time, datetime, timedelta, tzinfo and, timezone. The date class represents just a date, the time object represents the time independent of date, and datetime represents both the date and time.
Further, we also showed how datetime objects can be created in various ways – using a constructor, combining date and time objects, etc. We also explored formatting: strftime allows us to represent a date/time/datetime object as a string using a format string as guide. strptime uses a format string to convert a string containing the date, time into a datetime object.
However, there is more to learn from here. Though this article does not cover it, the module supports the creation and manipulation of date and times in various time zones, which gives you even more power for your Python programming needs. You can also explore other concepts related to dates, such as getting Daylight Saving Time information, more techniques for dealing with the local time zone, and beyond.
Regardless, with these tools, you can quickly achieve success and build the programs to your desire. We wish you the best of luck with your Python programs!
FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.