How to Use the Datetime Module in Python – Beginner’s Guide

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.month

>>> d.year

# Monday = 0, Sunday = 6
>>> d.weekday()

# Monday = 1, Sunday = 7
>>>> d.isoweekday()

>>> d.replace (month=11), 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)

# the latest representable date
>>> print (date.max)

# the smallest possible difference between 2 non-equal date objects.
>>> print (date.resolution)
1 day, 0:00:00

Photo of an hour glass on rocks

Formatting date

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

>>> d.ctime()
'Wed May 26 00:00:00 1999'

>>> d.strftime('%d%m%y')

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
>>> t.second

>>> t.minute

>>> t.microsecond

>>> t.isoformat() 

>>> t.strftime('%H:%M:%S') 

# New date from existing date by replacing minute
>>> t2 = t.replace(minute=44) 

>>> t2.isoformat()

# new time from isoformatted string
>>> t3 = time.fromisoformat('14:45:59')

>>> t3
datetime.time(14, 45, 59)

>>> t3.isoformat()

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')

# 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) 

# the latest representable time 
>>> print (date.max) 

# the smallest possible difference between 2 non-equal time objects. 
>>> print (date.resolution) 

People looking at the sky from inside a clock


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)

# total difference in seconds
>>> (dt2 - dt1).total_seconds()


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

>>> d.month


>>> d.hour 

>>> d.minute

>>> d.second

>>> d.isoformat()

>>> d.timestamp()
932754419.0 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 =
print (now)

# yyyy-mm-dd hh:mm:ss.microseconds
2021-07-26 16:39:07.104867

# day
>>> print (

# month
>>> print (now.month)

>>> print (now.hour)

# minute
>>> print (now.minute)

>>> iso format
print (now.isoformat())

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)

Pile of wooden clocks

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 =
>>> today
datetime.datetime(2021, 7, 27, 15, 25, 8, 89016)

# thirty_days is a timedelta object
>>> thirty_days = timedelta(days=30)
>>> thirty_days

>>> 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 =

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

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

# timestamp => datetime
>>> ts = dt.timestamp()
>>> dt2 = datetime.fromtimestamp(ts)
>>> dt2
datetime.datetime(2002, 7, 24, 7, 18, 22)

Additional Reading/References

Ready to learn more about Python datetime or Python in general? Explore some of the links below!


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.