Home > Backend Development > Python Tutorial > How can we convert a Python datetime object to milliseconds since the epoch?

How can we convert a Python datetime object to milliseconds since the epoch?

DDD
Release: 2024-11-18 22:39:02
Original
465 people have browsed it

How can we convert a Python datetime object to milliseconds since the epoch?

Converting Datetime Objects to Unix Time in Python

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template