Categories
Python Answers

How to convert a datetime object to milliseconds since epoch (unix time) in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *