Sometimes, we want to convert a datetime object to milliseconds since epoch (unix time) in Python.
In this article, we’ll look at how to convert a datetime object to milliseconds since epoch (unix time) in Python.
How to convert a datetime object to milliseconds since epoch (unix time) in Python?
To convert a datetime object to milliseconds since epoch (unix time) in Python, we can get a timedelta object by subtracting the datetime object by the datetime object at epoch.
For instance, we write
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
to create the unix_time_millis
to subtract datetime dt
with epoch
to get a timedelta object with their difference.
Then we call total_seconds
to seconds between dt
and epoch
.
Finally we multiply that by 1000 to get the difference in milliseconds.
Conclusion
To convert a datetime object to milliseconds since epoch (unix time) in Python, we can get a timedelta object by subtracting the datetime object by the datetime object at epoch.