Home > Backend Development > Python Tutorial > How can I convert a Python datetime object to Unix time (seconds/milliseconds since the 1970 epoch)?

How can I convert a Python datetime object to Unix time (seconds/milliseconds since the 1970 epoch)?

Patricia Arquette
Release: 2024-11-14 18:31:02
Original
331 people have browsed it

How can I convert a Python datetime object to Unix time (seconds/milliseconds since the 1970 epoch)?

Converting Datetime Objects to Epoch Time (Unix Time) in Python

In Python, converting datetime objects to Unix time, or milliseconds since the 1970 epoch, is a common task. The following question delves into how to accomplish this conversion effectively:

Question:

How can I convert a Python datetime object to unix time, or seconds/milliseconds since the 1970 epoch?

Answer:

One of the most straightforward solutions is to utilize the "unix_time_millis" function, as demonstrated below:

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

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

Explanation:

  1. import datetime: This line imports the datetime module, which provides the necessary functionality for handling date and time operations.
  2. epoch = datetime.datetime.utcfromtimestamp(0): This line defines the epoch, which represents the point in time from which Unix time is measured (January 1, 1970 at 00:00:00 UTC).
  3. def unix_time_millis(dt): This defines a function called "unix_time_millis" that takes a datetime object "dt" as its parameter.
  4. (dt - epoch): This calculates the time difference between the input datetime "dt" and the epoch.
  5. .total_seconds(): This converts the time difference from a timedelta object to a float representing the total number of seconds.
  6. * 1000.0: This multiplies the number of seconds by 1000 to convert it to milliseconds.

By using this function, you can effortlessly convert any datetime object to Unix time in milliseconds.

The above is the detailed content of How can I convert a Python datetime object to Unix time (seconds/milliseconds since the 1970 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template