DEV Community

Cover image for Python How-To: Working With Dates And Times In Python
dev_neil_a
dev_neil_a

Posted on • Updated on

Python How-To: Working With Dates And Times In Python

Introduction

Working with dates and times is something that comes up frequently when building solutions with any programming language. Most languages, including Python, will have a library built-in that can be used to work with dates and time.

For Python, there is a built-in library called datetime that can be used to simplify working with dates and time based date.

Using The datetime Python Library

As the datetime library is built-into Python, there is nothing, other than Python to install. Let us look at some examples of how to use the datetime library.

Displaying The Current Date And Time

First, let's get the current date and time:

import datetime

print(f"Current Date & Time: {datetime.datetime.now()}")
Enter fullscreen mode Exit fullscreen mode

Output:

Current Date & Time: 2023-04-22 20:04:05.506534
Enter fullscreen mode Exit fullscreen mode

Using the datetime.datetime.now() method provides both the current date and time of the system it is run on.

By default, the date is formatted as year-month-day. This is known as the ISO 8601 standard date format.

Displaying The Current Date

Now let's get just the current date:

import datetime

print(f"Date: {datetime.datetime.now().date()}")
Enter fullscreen mode Exit fullscreen mode

Output:

Date: 2023-04-22
Enter fullscreen mode Exit fullscreen mode

The syntax is very much the same as getting the date and time but adding .date() to the end will display only the date.

Displaying The Current Time

Next, let's get just the current time:

import datetime

print(f"Time: {datetime.datetime.now().time()}")
Enter fullscreen mode Exit fullscreen mode

Output:

Time: 20:04:05.506567
Enter fullscreen mode Exit fullscreen mode

This is basically the same as getting just the date but instead of adding .date() to the end, adding .time() returns just the time.

Calculate The Difference Between Two Dates

Working out the difference between two dates and / or times is something that is done frequently. First, let's look at an example of how to work out the time difference between two dates:

import datetime

date_one = datetime.date(year=2023, month=4, day=22)
date_two = datetime.date(year=2022, month=3, day=22)

print(f"The time difference is: {date_one - date_two}")
Enter fullscreen mode Exit fullscreen mode

Output:

The time difference is: 396 days, 0:00:00
Enter fullscreen mode Exit fullscreen mode

For each of the two date variables, a date is specified using the datetime.date() method, with a year, month and day specified for each.

From there, a simple subtraction of one from the other is performed to work out the difference.

Calculate The Difference Between Two Times

Now, let's look at another example but instead of showing the difference between two dates, show the difference between two times:

import datetime

time_one = datetime.timedelta(hours = 15, minutes = 52)
time_two = datetime.timedelta(hours = 13, minutes = 58)

print(f"The time difference is: {time_one - time_two}")
Enter fullscreen mode Exit fullscreen mode

Output:

The time difference is: 1:54:00
Enter fullscreen mode Exit fullscreen mode

This is very similar to the previous date example but it uses the timedelta() method to set the time. Using the time() method is not an option as it doesn't allow for mathematical operations to be performed against it.

Calculate The Difference Between Two Dates And Times

To wrap up working out the differences between two dates or times, let's take a look at an example of how to work out the difference between two dates and times:

import datetime

date_time_one = datetime.datetime(year = 2023, month = 4, day = 22, 
                                  hour = 11, minute = 52)
date_time_two = datetime.datetime(year = 2022, month = 3, day = 22, 
                                  hour = 13, minute = 58)

print(f"The time difference is: {date_time_one - date_time_two}")
Enter fullscreen mode Exit fullscreen mode

Output:

The time difference is: 395 days, 21:54:00
Enter fullscreen mode Exit fullscreen mode

This method basically uses the same method as working out the difference between two dates with additional arguments being passed for the hours and minutes. Seconds and milliseconds can also be passed, if needed.

Converting Between Date Formats

Working with different formatted dates is another common occurrence. There are three main date formats that are typically used:

  • Year, Month, Day (ISO standard, which is Python's default format)
  • Day, Month, Year (European standard)
  • Month, Day, Year (U.S.A standard)

Converting between these formats in Python is easy to do with the datetime library. The following example will show how to convert from the ISO format to both the European and U.S.A standard formats:

import datetime

current_date = datetime.datetime.now()

print(f"Default Date Format: {current_date.date()}")
print(f"Current Time: {current_date.strftime('%H:%M:%S')}\n")
print(f"U.S.A Date Format: {current_date.strftime('%m/%d/%Y')}")
print(f"European Date Format: {current_date.strftime('%d/%m/%Y')}")
Enter fullscreen mode Exit fullscreen mode

Output:

Default Date Format: 2023-04-22
Current Time: 20:04:05

U.S.A Date Format: 04/22/2023
European Date Format: 22/04/2023
Enter fullscreen mode Exit fullscreen mode

The above example sets the current_date variable to the current date and time. That is then used to convert the date using the strftime() method to the format that is required.

To explain what the %m/%d/%Y and %d/%m/%Y mean inside the strftime() method:

  • %m is the month as a number.
  • %d is the day.
  • %Y is the full year (2023 for example).
  • / is used as the divider. It can be anything but it is best to use / or a -.

If the month needs to be the full name, rather than a number, change it from %m to %B.

The date would then be April/22/2023 or 22/April/2023. This output format doesn't look ideal so change the output format to %B %d, %Y (April 22, 2023) or %d %B, %Y (22 April, 2023), both of which are more standard formats.

Working With Dates / Times In Different Timezones

Last but not least, let's take a look at working with different timezones.

There is a built-in method within the datetime library for handling timezones but there is a simpler solution for it in the form of a third-party library called [pytz](https://pypi.org/project/pytz/.

This library isn't installed with Python so it will need to be installed using pip:

pip install pytz
Enter fullscreen mode Exit fullscreen mode

Once it is installed, it can be imported and then be called to show all of the timezones available in the library using the .all_timezones method.

import datetime
import pytz

print(pytz.all_timezones)
Enter fullscreen mode Exit fullscreen mode

The output is far too long to show but all of the options in the (Python) list it produces can be used to take a date and time and convert it to the appropriate timezone. It won't however though convert the date format to the region of that timezone so that will need to be done manually, if required.

The following example will show a number of timezone conversions for different timezones in different regions / continents:

import datetime
import pytz

# --- Local time:
local_date_time = datetime.datetime.now()
print(f"Local Time: {local_date_time.strftime('%d/%m/%Y, %H:%M:%S')}\n")


# --- Time in Paris, France:
tz_paris = pytz.timezone("Europe/Paris")
paris_date_time = datetime.datetime.now(tz = tz_paris)
print(f"Paris Time: {paris_date_time.strftime('%d/%m/%Y, %H:%M:%S')}\n")


# --- Time in Canberra, Australia:
tz_canberra = pytz.timezone("Australia/Canberra")
canberra_date_time = datetime.datetime.now(tz = tz_canberra)
print(f"Canberra Time: {canberra_date_time.strftime('%d/%m/%Y, %H:%M:%S')}\n")


# --- Time in Washington D.C, U.S.A:
tz_dc = pytz.timezone("US/Eastern")
dc_date_time = datetime.datetime.now(tz = tz_dc)
print(f"Washington D.C Time: {dc_date_time.strftime('%m/%d/%Y, %H:%M:%S')}\n")
Enter fullscreen mode Exit fullscreen mode

Output:

Local Time: 22/04/2023, 20:04:05

Paris Time: 22/04/2023, 21:04:05

Canberra Time: 23/04/2023, 05:04:05

Washington D.C Time: 04/22/2023, 15:04:05
Enter fullscreen mode Exit fullscreen mode

To go over what the code did, let's take the Washington D.C example as they are all the same, except for the local time example and the date format.

  • tz_dc - This sets the variable to the US/Eastern timezone.
  • dc_date_time - This gets the date and time as normal but passing the tz = dc_date_time argument will set the date and time to that in the US/Eastern timezone.
  • The print statement output will be the date and time in the US/Eastern timezone and in the format used in the U.S.A. That format can be changed as it was manually set.

Conclusion

Working with dates and times is something that is done a lot in Python (along with other languages). The examples shown are some of the most common tasks that are performed.

There are many other options for working and manipulating date and time data so feel free to look at the documentation in the references section.

In closing, I hope this article was useful and have a nice day!

References

Documentation for the datetime library:

https://docs.python.org/3/library/datetime.html

Documentation for the pytz timezone library:

https://pypi.org/project/pytz/

Top comments (0)