Home >Backend Development >Python Tutorial >How to Convert a Datetime Object to Milliseconds Since Epoch in Python?
Convert Datetime to Milliseconds Since Epoch in Python
A common task in programming is converting a datetime object to milliseconds since epoch. This is especially useful for storing and transmitting timestamps in a consistent and efficient manner.
Solution:
Python provides a straightforward way to accomplish this conversion using the datetime module. Here's how you can do it:
import datetime
def unix_time_millis(dt): epoch = datetime.datetime.utcfromtimestamp(0) return (dt - epoch).total_seconds() * 1000.0
Usage:
To use this function, simply pass your datetime object as an argument:
timestamp = unix_time_millis(datetime.datetime.now())
The timestamp will be a float representing the milliseconds since epoch for the current date and time.
The above is the detailed content of How to Convert a Datetime Object to Milliseconds Since Epoch in Python?. For more information, please follow other related articles on the PHP Chinese website!