How to Convert DateTime to UNIX timestamp in Python

Published on Aug. 22, 2023, 12:16 p.m.

To convert a datetime object to a UNIX timestamp in Python, you can use the time.mktime() function from the built-in time module. This function takes a struct_time object (which can be obtained from a datetime object using the timetuple() method) as input and returns the corresponding UNIX timestamp in seconds.

Here’s an example:

import datetime
import time

my_datetime = datetime.datetime(2022, 2, 19, 12, 0, 0)
unix_timestamp = int(time.mktime(my_datetime.timetuple()))

print(unix_timestamp)   # Output: 1645288800

In this example, we define a datetime object my_datetime containing the value of February 19, 2022 at 12:00:00. We use the timetuple() method to convert the datetime object to a struct_time object, which is then passed to the time.mktime() function to convert it to a UNIX timestamp in seconds. The resulting value in unix_timestamp is equivalent to the number of seconds that have elapsed since the UNIX epoch (January 1, 1970 at 00:00:00 UTC) to the input datetime object.

Note that the UNIX timestamp is typically represented as an integer, so we use the int() function to convert the output of time.mktime() to an integer.

In general, converting a datetime object to a UNIX timestamp can be useful when you need to perform datetime arithmetic or when passing datetime values as arguments to functions that expect UNIX timestamps.

Tags:

related content