Back to articles list Articles
7 minutes read

How to Work with Date and Time in Python

Working with date and time data in Python is an important skill. This article will demonstrate the most important Python date and time modules.

Working with dates and times in Python can present some unique challenges. The number of days in a month can change, which can complicate a seemingly simple calculation of the number of days between two dates. Leap years make this more complex if you’re working with data spanning several years. Different time zones also need to be considered if you want to analyze timeseries data from different states or countries. This means that we can’t simply represent dates and times by integers if we want to calculate a difference or to compare them.

There are a few handy Python modules that provide functionality to make dealing with dates and times easier. We’ve previously discussed some great libraries Python has to offer; in this article, we’ll introduce (with examples) some of the most useful tools for handling dates and times.

If you’re new to Python, we have plenty of material to get you on your feet. A good place to start is our Python Basics courses. Here’s Part 1, Part 2, and Part 3. All courses contain interactive exercises designed to accelerate your learning.

The time Module

The first module is called time and comes with the standard installation of Python. Let’s start by getting the current time:

>>> import time
>>> time_now = time.time()
>>> print(time_now)
... 1653035191.6578639

Try this for yourself. The output you get will change depending on when you execute this command. However, this command returns a very large number. This is the time (in seconds) that has elapsed since a reference time, or ‘epoch’. For most systems, the epoch is Thursday 1st January 1970 at 00:00:00 UTC. Dates and times before this epoch are expressed as a negative number. Having the time displayed in seconds since 1970 isn’t particularly useful, so it can be displayed as a pre-formatted string:


>>> print(time.ctime(time_now))
... Fri May 20 10:26:31 2022

Here, we’ve used the ctime() method to convert the elapsed seconds to a more familiar format.

The time() function can be used to check the run time of a block of code, which can be very valuable information when writing more complex programs. Another interesting function from this module is sleep(), which can pause the execution of a program for a certain number of seconds. The following example shows both of these functions in action:

>>> t1 = time.time()
>>> for i in range(4):
...     print(i)
...     time.sleep(1)
>>> t2 = time.time()
>>> print('Runtime: %s seconds'%(t2 - t1))
0
1
2
3
Runtime: 4.030589818954468 seconds

Here we’re timing the whole for loop. In the loop, we’re simply printing the index and then sleeping for 1 second. Check out this article for more information on Python’s print() function. The final runtime will depend on the system but should be a little more than 4 seconds. This module has much more functionality than we can show here, so check out the documentation for more details. 

The calendar Module

The calendar module provides functions related to outputting calendars. It also comes with the standard installation of Python.

The calendar() function simply prints the calendar for the whole year. Just give the year, as an integer, as the first argument. The output is a string with spaces and newline characters to display the calendar nicely. Similarly, the month() function accepts the year and month as integer arguments and outputs the calendar for that month. You can read this article if you need help working with strings in Python.

If you test these functions, you’ll notice that the calendars use Monday as the first day of the week, which has the index 0. You can get the weekday number, from 0 to 6, for any date using the weekday() function. This standard of starting the week from Monday, at index 0, is also used in other Python modules.

The Calendar class includes some iterators that you can use to iterate through the days of the week and months of the year. There is also a TextCalendar and a HTMLCalendar class, which can generate plain text and HTML calendars. Once again, check out the documentation for more details on this module.

The datetime Module

With the help of the datetime module, you can define dates and times as an object. As stated in the documentation, the focus of this module is on efficient attribute extraction for displaying and manipulating datetime objects. But it’s not limited to this; you can also use it to calculate the number of days between two dates. To define a datetime object, import the module and do the following:

>>> import datetime
>>> date1 = datetime.datetime(2022, 1, 1, 12, 30, 0)

The arguments define the date from the year down to the microsecond, with the year, month, and day being required arguments. You can also optionally include time zone information when defining the datetime object. If you try to define an invalid date, for example with the argument day = 35, you’ll get ValueError: day is out of range for month.

The datetime object has many methods associated with it. You can retrieve the year with date1.year, which returns an integer. This also works for the other date and time information down to the microsecond. As we discussed previously, the day of the week (as an integer between 0 and 6) can be retrieved using the weekday() function:

	>>> print(date1.weekday())
	... 5

The integer 5 corresponds to a Saturday. You can double check this by printing the calendar using the calendar module. Try it yourself.

Let’s create another datetime object:

	>>> date2 = datetime.datetime(2021, 7, 31)

The difference between the two dates can be easily calculated and printed:

>>> time_diff = date1 - date2
>>> print('Number of days between %s and %s = %s'%(date1, date2, time_diff.days))

Number of days between 2022-01-01 12:30:00 and 2021-07-31 00:00:00 = 154

This creates a new timedelta object, which represents a duration. We used the days() method to get the time difference in days, then printed the answer. Even if the time difference spans multiple years, the coarsest resolution of the timedelta object will be in days.

In the example above, we simply displayed the object using the print() function. The default format when the object is printed in this way is YYYY-MM-DD HH:MM:SS. The datetime module comes with some handy functionality to help format and display objects. For example,  strftime() is an instance method that allows you to create a string representation of a datetime object. Here are a few examples of how to use different format strings to print date and time information using this method:

>>> print(date1.strftime('%Y %m %d'))
... 2022 01 01

>>> print(date1.strftime('%Y-%m-%d'))
... 2022-01-01

>>> print(date1.strftime('%A %d %B %Y'))
... Saturday 01 January 2022

>>> print(date1.strftime('%a %d %b %y, %H:%M:%S %p'))
... Sat 01 Jan 22, 12:30:00 PM

There are many more options for formatting a date/time output string. Take a look at the format codes for some inspiration.

Related to this is the class method strptime(). It does the reverse of the previous example, namely going from a string to a datetime object. This method has two required arguments: a date string and a format string. You use the same format codes as mentioned above. Here’s an example:

>>> date3 = datetime.datetime.strptime('2022-01-01', '%Y-%m-%d')
>>> print(date3)
2022-01-01 00:00:00

Working in Different Time Zones

The last feature we’ll demonstrate is how to handle time zones. When you create a datetime object, you can define the time zone with the help of the pytz library. For a full list of time zones, simply execute pytz.common_timezones in the terminal, which will print a list of strings. We can choose a few time zones and check the current time:

>>> import pytz
>>> time_zones = ['America/New_York', 'Asia/Seoul', 'Australia/Melbourne', 'Europe/Zagreb']
>>> for time_zone in time_zones:
... 	print(datetime.datetime.now(tz=pytz.timezone(time_zone)))
2022-05-20 04:26:34.134504-04:00
2022-05-20 17:26:34.134504+09:00
2022-05-20 18:26:34.134504+10:00
2022-05-20 10:26:34.134504+02:00

These datetime objects are now ‘aware’ and can only play nicely with other timezone-aware objects. Try calculating the time difference between an aware and a naive object and you’ll get a TypeError.

Take Your Time and Learn Python

Working with dates and times is an important skill in many aspects of programming. There’s much more to it than we can cover in one article. Check out this article, where we touch on many of the topics we discussed here and show some interesting examples. With a bit of time and practice, you’ll master another important Python skill.