"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do you Convert Python Datetime Objects to Milliseconds Since Epoch?

How do you Convert Python Datetime Objects to Milliseconds Since Epoch?

Published on 2024-11-17
Browse:566

How do you Convert Python Datetime Objects to Milliseconds Since Epoch?

Converting Datetime Objects to Milliseconds Since Epoch in Python

Python's datetime object provides a robust way to represent dates and times. However, certain situations may require converting datetime objects into milliseconds since the UNIX epoch, representing the number of milliseconds elapsed since January 1, 1970, at midnight Coordinated Universal Time (UTC).

To achieve this conversion, the following steps can be taken:

1. Import the Datetime Module:

import datetime

2. Define the UNIX Epoch as a Datetime Object:

The UNIX epoch is a fixed point in time represented as a datetime object:

epoch = datetime.datetime.utcfromtimestamp(0)

3. Create a Unix Time Conversion Function:

To convert a datetime object to milliseconds since the epoch, you can use the following function:

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0

This function takes a datetime object as input and subtracts the epoch datetime object. The resulting timedelta object represents the number of seconds elapsed since the epoch. Multiplying this by 1000.0 converts the value to milliseconds.

Example Usage:

To convert a given datetime object to milliseconds since the epoch:

import datetime

dt = datetime.datetime(2023, 1, 1, 10, 30, 15)
unix_time_milliseconds = unix_time_millis(dt)

print(unix_time_milliseconds)

This would output the number of milliseconds since the epoch at the specified datetime object.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3