Home >Backend Development >Python Tutorial >How to Convert a Datetime Object to Milliseconds Since Epoch in Python?

How to Convert a Datetime Object to Milliseconds Since Epoch in Python?

DDD
DDDOriginal
2024-11-19 00:30:031057browse

How to Convert a Datetime Object to Milliseconds Since Epoch in Python?

Convert Datetime to Milliseconds Since Epoch in Python

A common task in programming is converting a datetime object to milliseconds since epoch. This is especially useful for storing and transmitting timestamps in a consistent and efficient manner.

Solution:

Python provides a straightforward way to accomplish this conversion using the datetime module. Here's how you can do it:

  1. Import the datetime module:
import datetime
  1. Create a unix_time_millis() function that calculates the milliseconds since epoch for a given datetime object:
def unix_time_millis(dt):
    epoch = datetime.datetime.utcfromtimestamp(0)
    return (dt - epoch).total_seconds() * 1000.0
  • The datetime.datetime.utcfromtimestamp(0) line creates a datetime object representing the epoch (January 1, 1970 at 00:00:00 UTC).
  • The function then subtracts the epoch datetime from the input datetime object (dt) and multiplies the result by 1000.0 to convert from seconds to milliseconds.

Usage:

To use this function, simply pass your datetime object as an argument:

timestamp = unix_time_millis(datetime.datetime.now())

The timestamp will be a float representing the milliseconds since epoch for the current date and time.

The above is the detailed content of How to Convert a Datetime Object to Milliseconds Since Epoch in Python?. 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