This post will discuss how to convert the datetime object to milliseconds since the epoch in Python.

1. Using timedelta.total_seconds() function

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta.total_seconds() * 1000.

Download  Run Code

2. Using datetime.timestamp() function

Starting with Python 3.3, you can use the datetime.timestamp() function to get the Epoch timestamp in seconds as a floating-point number. Since datetime instances are assumed to represent local time, you should first convert the datetime object to UTC. This can be done with dt.replace(tzinfo=timezone.utc).

Download  Run Code

3. Using delorean module

If you’re already using the delorean module, consider using its epoch attribute, which returns Epoch time in seconds.

Download Code

That’s all about converting datetime objects to milliseconds since the epoch in Python.