Set datetime to Unix Timestamp in Python (2 Examples)

This post explains how transform a datetime object to a unix timestamp in Python.

Loading datetime Module & Creating Example Data

To load the datetime module, you can use the code below:

import datetime

Then we generate the following datetime object:

datetime_x = datetime.datetime.now()
print(datetime_x)
# 2022-03-22 10:42:31.784553

Example 1: Set datetime to Unix Timestamp Using timestamp() Function

To get the right result, have to multiply the output of the timestamp function by 1000:

timestamp_x_1 = datetime_x.timestamp() * 1000
print(timestamp_x_1)
# 1647942151784.553

Example 2: Set datetime to Unix Timestamp Using timetuple() & mktime() Functions

In this case we use the timetuple() and mktime() functions to transform our datetime to unix timestamp.

For this we first have to load the time module to Python:

import time

Then we can apply those functions to convert our data. Consider the Python code and its output:

timestamp_x_2 = time.mktime(datetime_x.timetuple())
print(timestamp_x_2)
# 1647942151.0

The previous timestamp represents our date and time in seconds, not in microseconds as in the first example.

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top