When working with date and time data, it is often necessary to convert them to a common format for comparison and calculations. Unix time, which represents the number of seconds or milliseconds that have elapsed since the epoch (January 1, 1970, UTC), is a widely used format.
Question: How can we seamlessly convert a Python datetime object to milliseconds since the epoch?
Answer:
To achieve this conversion, we can utilize the following approach:
import datetime # Define the epoch as a datetime object epoch = datetime.datetime.utcfromtimestamp(0) # Function to convert datetime to Unix time in milliseconds def unix_time_millis(dt): # Subtract the epoch from the datetime object to get the time difference as a timedelta object. time_diff = dt - epoch # Convert the timedelta object to seconds and multiply by 1000 to get milliseconds. return time_diff.total_seconds() * 1000.0
By utilizing this straightforward function, you can effortlessly obtain the Unix time in milliseconds from any Python datetime object.
The above is the detailed content of How can we convert a Python datetime object to milliseconds since the epoch?. For more information, please follow other related articles on the PHP Chinese website!