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

DDD
Release: 2024-11-17 16:30:01
Original
426 people have browsed it

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

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

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

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

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

The above is the detailed content of How do you Convert Python Datetime Objects to Milliseconds Since 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