Python 3: Convert Datetime to Timestamp and vice versa

Last updated on November 5, 2021 Pennywise Loading... Post a comment

This article shows you a couple of different ways to convert datetime instances into timestamps and vice versa in Python 3.

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:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles