如何將 Python DateTime 字串轉換為毫秒整數?


在本文中,我們將討論在 Python 中將 Python datetime 字串轉換為毫秒的各種方法。

使用 time.time() 方法

Python 中的 time 模組提供了各種與時間相關的函式和方法。在這裡,我們使用 time.time() 方法獲取當前 CPU 時間(以秒為單位)。時間是從紀元開始計算的,它返回一個以秒錶示的浮點數。此值乘以 1000 並使用 round() 函式四捨五入。

注意:紀元是時間的起點,並且依賴於平臺。在 Windows 和大多數 Unix 系統上,紀元是 1970 年 1 月 1 日 00:00:00 (UTC),並且紀元以來的秒數中不包括閏秒。

我們使用 time.gmtime(0) 獲取給定平臺上的紀元。

語法

time() 方法的語法如下所示。

time.time()

返回一個表示紀元以來的秒數的浮點值。

示例

在以下示例程式碼中,我們使用 time.time() 方法獲取當前時間(以秒為單位)。然後乘以 1000,並使用 round() 函式對值進行近似。

import time
obj = time.gmtime(0)
epoch = time.asctime(obj)
print("The epoch is:",epoch)
curr_time = round(time.time()*1000)
print("Milliseconds since epoch:",curr_time)

輸出

以上程式碼的輸出如下所示:

The epoch is: Thu Jan  1 00:00:00 1970
Milliseconds since epoch: 1662373873162

使用 datetime 模組

在這裡,我們使用 datetime 模組提供的各種函式來查詢當前時間並將此字串轉換為毫秒整數。

最初,我們使用 datetime.utc() 方法檢索當前日期。然後,我們透過從當前日期減去 1670 年 1 月 1 日 (datetime(1970, 1, 1)) 獲取自紀元以來的天數。對於此日期,我們應用 .total_seconds() 返回自紀元以來的秒總數。最後,我們透過應用 round() 函式將值四捨五入到毫秒。

示例 1

在以下示例程式碼中,我們獲取當前時間字串並將其轉換為毫秒整數。

from datetime import datetime
print("Current date in string format:",datetime.utcnow())
date= datetime.utcnow() - datetime(1970, 1, 1)
print("Number of days since epoch:",date)
seconds =(date.total_seconds())
milliseconds = round(seconds*1000)
print("Milliseconds since epoch:",milliseconds)

輸出

以上示例程式碼的輸出如下所示:

Current date in string format: 2022-09-05 10:31:52.853660
Number of days since epoch: 19240 days, 10:31:52.853671
Milliseconds since epoch: 1662373912854

示例 2

timestamp() 函式用於將 datetime 物件轉換為毫秒 -

import time
from datetime import datetime
dt = datetime(2018, 1, 1)
milliseconds = int(round(dt.timestamp() * 1000))
print(milliseconds)

輸出

這將給出以下輸出

1514745000000

更新於: 2023 年 4 月 4 日

5K+ 次觀看

啟動您的 職業生涯

透過完成課程獲得認證

立即開始
廣告