Python 3: Convert Datetime to Timestamp and vice versa
( 48 Articles)

This article shows you a couple of different ways to convert datetime instances into timestamps and vice versa in Python 3.
Table of Contents
Datetimes to Timestramps
Approach 1: Using the timestramp() method
Example:
from datetime import datetime, timezone
my_dt = datetime(2021, 11, 5, 15, 20, 20)
my_timestamp = dt1.replace(tzinfo=timezone.utc).timestamp()
my_timestamp
Output:
1636125620.0
Approach 2: Doing some math operations
Example:
from datetime import datetime, timezone, timedelta
my_dt = datetime(2021, 11, 6, 14, 25, 59)
my_timestamp = (my_dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
my_timestamp
Output:
1636208759.0
Timestramp into Datetimes
The datetime.fromtimestamp function can help us get the job done quickly.
Example:
from datetime import datetime
timestamp = 1636208759.0
dt = datetime.fromtimestamp(timestamp)
# UTC: dt = datetime.utcfromtimestamp(timestamp)
dt
Output:
datetime.datetime(2021, 11, 6, 14, 25, 59)
Conclusion
You’ve learned how to turn datetime objects into timestamps and vice versa in modern Python. If you’d like to explore more new and interesting things about the awesome programming language, take a look at the following articles:
- Python 3: Formatting a DateTime Object as a String
- Python reduce() function examples
- Examples of using Lambda Functions in Python 3
- How to Install Python Libraries in Google Colab
- Extract all links from a webpage using Python and Beautiful Soup 4
You can also check out our Machine Learning category page or Python category page for more tutorials and examples.
Subscribe
0 Comments