首頁  >  文章  >  後端開發  >  如何將 Python 日期時間物件轉換為 Unix 時間(自 1970 紀元以來的秒/毫秒)?

如何將 Python 日期時間物件轉換為 Unix 時間(自 1970 紀元以來的秒/毫秒)?

Patricia Arquette
Patricia Arquette原創
2024-11-14 18:31:02286瀏覽

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

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.

以上是如何將 Python 日期時間物件轉換為 Unix 時間(自 1970 紀元以來的秒/毫秒)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn