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 |
import datetime
Then we generate the following datetime object:
datetime_x = datetime.datetime.now() print(datetime_x) # 2022-03-22 10:42:31.784553 |
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 |
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 |
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 |
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.
- Set datetime to Different Time Zone in Python (3 Examples)
- Set datetime Object to Date Only String in Python (3 Examples)
- Transform datetime Object to Date & Vice Versa in Python (2 Examples)
- Transform datetime Object to Hours Minutes or Seconds in Python (3 Examples)
- Modify datetime Format in pandas DataFrame in Python (2 Examples)
- All Python Programming Tutorials
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.