Home >Backend Development >Python Tutorial >How to Convert Python datetime Objects to Milliseconds Since the Epoch?

How to Convert Python datetime Objects to Milliseconds Since the Epoch?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-18 21:46:02862browse

How to Convert Python datetime Objects to Milliseconds Since the Epoch?

Converting Datetime Objects to Milliseconds Since Epoch in Python

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:

  1. Import the datetime Module:

    import datetime
  2. 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)
  3. 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!

Statement:
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