Home >Backend Development >Python Tutorial >How to Convert Python datetime Objects to Milliseconds Since the Epoch?
One often encounters the need to convert a Python datetime object to its epoch time representation, which measures the duration since the Unix epoch, typically expressed in seconds or milliseconds. This is especially useful when working with timestamped data or integrating with external systems.
To achieve this conversion, we can leverage Python's datetime module and the following steps:
Import the datetime Module:
import datetime
Establish a Reference Epoch:
We'll establish a datetime object representing the Unix epoch, which is January 1, 1970, 00:00:00 UTC:
epoch = datetime.datetime.utcfromtimestamp(0)
Define a Unix Time Conversion Function:
To convert a datetime object to milliseconds since the epoch, we define the following function:
def unix_time_millis(dt): return (dt - epoch).total_seconds() * 1000.0
This function calculates the time difference between the input datetime object and the epoch, converts it to seconds, and then multiplies by 1000 to obtain the milliseconds representation.
For example, assuming we have a datetime object named dt that represents a specific time:
dt = datetime.datetime(2023, 3, 8, 14, 55, 32)
We can convert it to milliseconds since the epoch using our function:
milliseconds_since_epoch = unix_time_millis(dt)
This would provide the milliseconds that have elapsed since the Unix epoch at the time represented by the dt datetime object.
The above is the detailed content of How to Convert Python datetime Objects to Milliseconds Since the Epoch?. For more information, please follow other related articles on the PHP Chinese website!