How to convert a date to Unix epoch time in Python?
You can convert a date to Unix epoch time in Python using the time
module and the mktime()
function.
Here is an example of converting a date to Unix epoch time:
from time import mktime
from datetime import datetime
# Define the date you want to convert
date = datetime(2022, 1, 1)
# Convert the date to a timestamp
timestamp = mktime(date.timetuple())
print(timestamp)
The mktime()
function takes a struct_time object as an argument and returns the corresponding Unix timestamp. The datetime.timetuple()
method returns a struct_time object, which can be passed to the mktime()
function. The resulting timestamp will be in seconds since the Unix epoch.
Alternatively, you can use the datetime.timestamp()
method that returns the timestamp directly.
timestamp = date.timestamp()
Both the above examples will give you the unix timestamp for the date 1st Jan 2022.
Please note that the datetime.timestamp()
was introduced in Python version 3.3 and above and the mktime() is not available on Windows.