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 subtract the datetime from the epoch datetime.

And then we call total_seconds on the difference and multiply that by 1000.

For instance, we write:

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)


def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0


dt = datetime.datetime(2020, 1, 1)
print(unix_time_millis(dt))

We use datetime.datetime.utcfromtimestamp(0) to create the Unix epoch datetime.

Then we define the unix_time_millis function that subtracts dt from epoch and call total_seconds on the difference.

And then we multiply that by 1000 to get the difference in milliseconds,

Next, we call unix_time_millis with dt to return the difference of dt since the Unix epoch in milliseconds.

Therefore, print should print 1577836800000.0.

Conclusion

To convert a datetime object to milliseconds since epoch (Unix time) in Python, we can subtract the datetime from the epoch datetime.

And then we call total_seconds on the difference and multiply that by 1000.

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 *