如何在本地時區列印 Python datetime?


在 Python 日期和時間中處理時區的最佳方法是使用 pytz 和 tzlocal 模組。這些庫可以進行準確且跨平臺的時區計算。pytz 將 Olson tz 資料庫引入 Python。它還解決了夏令時結束時的模糊時間問題,你可以在 Python 庫參考 (datetime.tzinfo) 中瞭解更多關於這個問題的資訊。

在使用此模組之前,你需要使用以下命令安裝 −

$ pip install pytz tzlocal

範例

你可以透過以下步驟使用 pytz 庫 −

from datetime import datetime
from pytz import timezone
from tzlocal import get_localzone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
# Convert to local time zone
now_local = now_utc.astimezone(get_localzone())
print(now_local.strftime(format))

輸出

此程式碼將輸出以下結果 −

2018-01-03 07:05:50 UTC+0000
2018-01-03 12:35:50 IST+0530

更新於: 6 月 12 日 2020 年

2K+ 已檢視次數

開啟你的職業

完成課程認證

開始
廣告