如何在 Python 中獲取當前時間(以毫秒為單位)?


在本文中,我們將討論在 Python 中檢索當前時間(以毫秒為單位)的各種方法。

使用 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: 1662372570512

使用 datetime 模組

這裡我們使用 datetime 模組 提供的各種函式來查詢當前時間(以毫秒為單位)。

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

示例

在下面的示例程式碼中,我們使用 Python datetime 模組提供的不同函式來獲取當前時間(以毫秒為單位)。

from datetime import datetime print("Current date:",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: 2022-09-05 10:10:17.745855
Number of days since epoch: 19240 days, 10:10:17.745867
Milliseconds since epoch: 1662372617746

更新於:2023-08-23

78K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.