Python datetime: A Comprehensive Guide (with Examples)

Dealing with dates and times in Python programs is common. You might need to write programs that deal with dates, times, or both. Besides, you commonly want to format these dates differently, build them from strings, and calculate time differences.

In Python, you can use the built-in datetime module for time and date manipulation.

This is a comprehensive guide to the datetime module in Python.

You will learn many useful date and time-related tasks, such as calculating time differences, using time stamps, and handling timezones.

The datetime Module in Python

Python has an extensive module for handling dates and times. This module is called datetime. You can import the datetime module into your project with the import statement.

import datetime

What Does the datetime Module Have?

Before extensively using the datetime module, let’s have a closer look at what’s inside. You can check the contents of the datetime module with the dir() function.

import datetime
for item in dir(datetime):
    print(item)

Output:

MAXYEAR
MINYEAR
__builtins__
__cached__
__doc__
__file__
__loader__
__name__
__package__
__spec__
date
datetime
datetime_CAPI
sys
time
timedelta
timezone
tzinfo

Take a look at the names without __ in them. Those are the most useful members of the datetime module.

In this guide, you will learn how to use the date, datetime, time, and timedelta objects. After learning how to use these classes, you know how to create date objects, and time objects, calculate time differences, access specific date components, and much more.

Date Objects in Python: datetime.date

In Python, you can use the datetime module to create and handle date and time objects.

One of the most notable classes in the datetime module is the date class.

With the date class, you can build date objects from the year, month, and day parameters.

Let’s see some examples of the datetime.date class.

Create a Date Object for Representing a Date

Creating a Python date object from date components with datetime.date constructor

To create a new date object in your code, you can use the datetime.date() class. This class takes three arguments:

  • year
  • month
  • day

It returns a date object that represents the date with the given components.

For example, let’s create a date object for the date 2022-11-18:

import datetime

date = datetime.date(2022, 11, 18)
print(date)

Printing the date object shows a nice textual representation of the date:

2022-11-18

How to Get Current Date

Current date with datetime.date.today function

When working with dates, one of the most common tasks to do is to access the current date.

Instead of creating the current date from the date components as you saw in the previous example, you can call the dedicated .today() function. This creates the date object for the current date.

For example, let’s create a date object that represents today and print it out:

import datetime

today = datetime.date.today()
print(today)

Output:

2022-11-10

How to Get Date from a Timestamp

Get date from timestamp in Python

Timestamps are a common way to represent date objects. You commonly see timestamps stored in databases.

A timestamp represents the current date and time as seconds. So instead of being a combination of year, month, day, hour, minute, second, and timezone information, it’s just a single large value. The best part about timestamps is they are the same no matter where you are on the planet. Using timestamps allows for a nice and uniform way to work applications where users come from different time zones.

So chances are you are going to need to know how to convert a timestamp into a date object.

Creating a custom function for this would require careful thinking. Luckily, there’s a ready-made function for creating a date object from a timestamp, called date.fromtimestamp().

For example, let’s create a date object using the timestamp 1639457341:

from datetime import date

date = date.fromtimestamp(1639457341)
print(date)

Output:

2021-12-14

Read more about timestamps in computer science.

How to Access Time Components

In Python, you can easily access specific time components of a date object by their names.

For example, let’s print the year, month, and day of a date object:

from datetime import date

date = date.today()

# Accessing date components
print(date.year)
print(date.month)
print(date.day)

Output:

2022
11
10

Time Objects in Python: datetime.time

In the previous examples, you learned how to use the datetime.date class for creating and operating on dates in Python.

Another useful class that resides in the datetime module is called the datetime.time class. You can use this class to create time objects in your code.

How to Create a Time Object

Creating a time object from hours, minutes, and seconds
hh, mm, and ss are integers!

To represent time in Python, you can use the datetime.time class. A typical way to call this function is by passing it three parameters:

  • hh for hours
  • mm for minutes
  • ss for seconds

For example, let’s create a time object to represent 15:35:43:

from datetime import time

t = time(15, 35, 43)

print(t)

Output:

15:35:43

How to Access Time Components

Given a time object, you can easily access the different time components by their names using dot notation.

For example, let’s print the hour, minute, and second of a time instance:

from datetime import time

t = time(15, 35, 43)

print(t.hour)
print(t.minute)
print(t.second)

Output:

15
35
43

Date & Time Objects in Python: datetime.datetime

Thus far you’ve learned how to use the datetime module to create date objects and time objects separately:

  • datetime.date to represent date objects
  • datetime.time to represent time objects

More often than not, you’ll need a combination of these two, that is, you want to represent both date and time as a single object.

This is where you can use the datetime.datetime class.

What Is the datetime Object

In Python, the datetime module has a datetime class that allows you to represent both the date and time in a single object.

For example, let’s create two datetime objects:

from datetime import datetime

d1 = datetime(2022, 10, 28, 13, 54, 18, 326780)
print(d1)

d2 = datetime(2022, 10, 28)
print(d2)

Output:

2022-10-28 13:54:18.326780
2022-10-28 00:00:00

Notice how the d2 date object only specifies the date components year, month, and day but not the time components for hours, minutes, and seconds. This is perfectly fine. Just notice that when you do this, the datetime object defaults to using 00 for each time component.

How to Get Date Components

To get a specific date or time component of the datetime object, use the dot notation and specify the name of the component.

For example, let’s get the year, month, day, hour, minute, and second of the datetime object:

from datetime import datetime

d2 = datetime(2022, 10, 28, 13, 54, 18)

print(d2.year)
print(d2.month)
print(d2.day)
print(d2.hour)
print(d2.minute)
print(d2.second)

Output:

2022
10
28
13
54
18

One useful feature of the datetime object is you can also convert it to a timestamp to represent the date as seconds since the beginning of computer time. As discussed earlier, the timestamp is the same in all corners of the world. This makes it a useful format for storing date objects in databases.

from datetime import datetime

d2 = datetime(2022, 10, 28, 13, 54, 18)

print(d2.timestamp())

Output:

1666965258.0

Time Differences in Python: datetime.timedelta

When dealing with dates and times, you commonly need to know the time difference between two dates or times.

The datetime class comes with a useful class timedelta you can use to represent time differences in your projects.

How to Get Difference Between Two Times/Dates

Given two datetime objects, you can calculate the time difference between the two by subtracting one from the other.

For example, let’s get the time difference between two datetime objects:

from datetime import datetime

d1 = datetime(2022, 10, 28, 13, 54, 18)
d2 = datetime(2017, 9, 18, 23, 36, 29)

time_delta = d1 - d2

print(time_delta)

Output:

1865 days, 14:17:49

Notice that the data type of this time difference is timedelta.

You can verify this by checking the type of time difference in the previous example:

from datetime import datetime

d1 = datetime(2022, 10, 28, 13, 54, 18)
d2 = datetime(2017, 9, 18, 23, 36, 29)

time_delta = d1 - d2

print(type(time_delta))
print(time_delta)

Output:

<class 'datetime.timedelta'>
1865 days, 14:17:49

How to Get Difference Between timedelta Objects

Notice that you can also calculate the time difference between two timedelta objects.

For example:

from datetime import timedelta

td1 = timedelta(weeks = 5, days = 2, hours = 12, seconds = 53)
td2 = timedelta(days = 17, hours = 18, minutes = 34, seconds = 14)
td3 = td1 - td2

print("Timedelta difference =", td3)

Output:

Timedelta difference = 19 days, 17:26:39

How to Print a Negative timedelta Object

When calculating time differences, sometimes you might end up with a negative timedelta object. This happens if you subtract an earlier date from a more recent date.

For example, the time difference between 2017 and 2022 is -5 years. But you actually never say it’s “negative five years from 2022 to 2017” but “five years” instead.

To get rid of the negative value in front of a timedelta object, use the built-in abs() function.

For example:

from datetime import datetime

d1 = datetime(2022, 10, 28, 13, 54, 18)
d2 = datetime(2017, 9, 18, 23, 36, 29)

# -1865 days, 14:17:49
time_delta = d2 - d1

# Use abs to get rid of negative timedeltas
print(abs(time_delta))

Output:

1865 days, 14:17:49

How to Get Timedelta in Seconds

If you’re handling dates using timestamps, then it might make sense to express time differences in seconds too.

To get the time differences in seconds in Python, you can use the timedelta.total_seconds() method.

For example:

from datetime import datetime

d1 = datetime(2022, 10, 28, 13, 54, 18)
d2 = datetime(2017, 9, 18, 23, 36, 29)

time_delta = d1 - d2
print(time_delta.total_seconds())

Output:

161187469.0

Formatting Dates with datetime in Python

Formatting dates and times are important when you want to show meaningful dates to end users, for example.

There are many ways to express date and time. With dates, you commonly see:

  • dd/mm/yyyy hh:mm:ss
  • mm/dd/yyyy hh:mm:ss

And with time, you commonly see hh:mm:ss.

Next, let’s take a look at how you can format date objects in Python.

How to Format Dates with strftime() Function

The datetime module’s datetime class comes with strftime() method that lets you format the date and time in a custom format. To use this method, pass the format as a string to the method and mark date/time components with %-sign.

This is best demonstrated with examples.

For example, let’s format today’s date and time in three different formats:

from datetime import datetime

date = datetime.now()

# Get time only
f1 = date.strftime("%H:%M:%S")
print("time:", f1)

# Get date and time in mm/dd/YY H:M:S format
f2 = date.strftime("%m/%d/%Y, %H:%M:%S")
print("date f1:", f2)

# Get date and time in dd/mm/YY H:M:S format
f3 = date.strftime("%d/%m/%Y, %H:%M:%S")
print("date f2:", f3)

Output:

time: 13:44:32
date f1: 11/10/2022, 13:44:32
date f2: 10/11/2022, 13:44:32

Turn a String to datetime Object with strptime()

Sometimes you may find yourself working with date objects that come as strings like “15 June 2022”.

To easily convert a date string to an actual datetime object, you can use the datetime classes strptime() method. To make this method work, pass a string argument to the strptime() method that specifies the order of time components in the date string.

Once again, this is best demonstrated with examples.

Here are two examples:

from datetime import datetime

str_date_1 = "15 July, 2022"

datetime_obj = datetime.strptime(str_date_1, "%d %B, %Y")
print("str_date_1 object =", datetime_obj)

str_date_2 = "10/17/2022 19:13:12"

datetime_obj = datetime.strptime(str_date_2, "%m/%d/%Y %H:%M:%S")
print("str_date_2 object =", datetime_obj)

Output:

str_date_1 object = 2022-07-15 00:00:00
str_date_2 object = 2022-10-17 19:13:12

In the first example, the date components are

  • %d – The day of the month. Example: 01, 02, … , 31
  • %B – The name of the month in full. Example: March, July
  • %Y – The year in four digits. Example: 2021, 2019

In the second example, the date components are more clear:

  • %m for month
  • %d for date
  • % y for year
  • %H for hour
  • %M for minute
  • %S for second

How to Deal with Timezones in Python

In the datetime module, there are no easy ways to deal with time zones.

This is why you should rely on another Python library, pytz if you need to work with timezones.

Because this article is about the datetime module, I’ll keep it short here.

Here are some examples of creating datetime objects in different timezones using the datetime module with the pytz module:

from datetime import datetime
import pytz

print("Current local time:", datetime.now().strftime("%m/%d/%Y, %H:%M:%S"))

madrid_timezone = pytz.timezone("Europe/Madrid")
datetime_London = datetime.now(madrid_timezone)
print("Current time in Madrid:", datetime_London.strftime("%m/%d/%Y, %H:%M:%S"))

new_york_timezone = pytz.timezone("America/New_York") 
datetime_NY = datetime.now(new_york_timezone)
print("Current time in New York:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S"))

Output:

Current local time: 11/10/2022, 13:50:08
Current time in Madrid: 11/10/2022, 14:50:08
Current time in New York: 11/10/2022, 08:50:08

Summary

Today you learned how to use the datetime module in Python.

To recap, the datetime module lets you deal with times and dates in your code. The module allows for easy time formatting and other useful operations on date objects.

Thanks for reading. Happy coding!

Read Also