How to Convert DateTime to UNIX Timestamp in Python ?
Generating a UNIX timestamp from a DateTime object in Python involves converting a date and time representation into the number of seconds elapsed since January 1, 1970 (known as the Unix epoch). For example, given a DateTime representing May 29, 2025, 15:30, the UNIX timestamp is the floating-point number representing seconds passed since the epoch. Let’s explore different method to do this efficientely .
Using datetime.timestamp()
datetime.timestamp() is a method available on datetime objects in Python. It converts a datetime instance into a POSIX timestamp, which is the number of seconds (including fractions) elapsed since the Unix epoch January 1, 1970, 00:00:00 UTC.
import datetime
dt = datetime.datetime(2021, 7, 26, 21, 20)
res = dt.timestamp()
print(res)
Output
1627334400.0
Explanation:
- datetime.datetime(2021, 7, 26, 21, 20) creates a datetime for July 26, 2021, 9:20 PM.
- dt.timestamp() converts it to the number of seconds as a float since the Unix epoch (Jan 1, 1970, 00:00 UTC).
Using time.mktime()
time.mktime() is a function from the time module that takes a time tuple (such as one returned by datetime.timetuple()) and converts it into a Unix timestamp. However, this timestamp is based on the local timezone, not UTC.
import time
import datetime
dt = datetime.datetime(2021, 7, 26, 21, 20)
res = time.mktime(dt.timetuple())
print(res)
Output
1627334400.0
Explanation:
- datetime.datetime(2021, 7, 26, 21, 20) creates a datetime for July 26, 2021, 9:20 PM (local time).
- dt.timetuple() converts it to a time tuple.
- time.mktime() converts this local time tuple to a Unix timestamp (seconds since epoch).
Using timestamp()
You can get the current date and time using datetime.datetime.now(), then convert it to a Unix timestamp in seconds using .timestamp(). Multiplying by 1000 converts seconds into milliseconds, which is useful for higher precision timing or APIs that expect timestamps in milliseconds.
import datetime
now = datetime.datetime.now()
res = int(now.timestamp() * 1000)
print(res)
Output
1748514862867
Explanation:
- datetime.datetime.now() gets the current local date and time.
- .timestamp() converts it to seconds since the Unix epoch (UTC).
- Multiplying by 1000 converts seconds to milliseconds.
- int() converts the result to an integer (whole milliseconds).