Convert datetime object to milliseconds since epoch in Python
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
from datetime import datetime def timestamp(dt): epoch = datetime.utcfromtimestamp(0) return (dt - epoch).total_seconds() * 1000.0 if __name__ == '__main__': dt = datetime(2020, 1, 1) print(timestamp(dt)) # 1577836800000.0 |
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).
|
1 2 3 4 5 6 7 8 9 10 |
from datetime import datetime, timezone def timestamp(dt): return dt.replace(tzinfo=timezone.utc).timestamp() * 1000 if __name__ == '__main__': dt = datetime(2020, 1, 1) print(timestamp(dt)) # 1577836800000.0 |
3. Using delorean module
If you’re already using the delorean module, consider using its epoch attribute, which returns Epoch time in seconds.
|
1 2 3 4 5 6 7 8 9 10 11 |
from datetime import datetime import delorean def timestamp(dt): return delorean.Delorean(dt, timezone='UTC').epoch * 1000 if __name__ == '__main__': dt = datetime(2020, 1, 1) print(timestamp(dt)) # 1577836800000.0 |
That’s all about converting datetime objects to milliseconds since the epoch in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)