首頁 >後端開發 >Python教學 >如何在 Python 中將本機時間字串轉換為 UTC 時間字串?

如何在 Python 中將本機時間字串轉換為 UTC 時間字串?

Susan Sarandon
Susan Sarandon原創
2024-12-30 14:33:09916瀏覽

How Can I Convert a Local Time String to a UTC Time String in Python?

將本地時間字串轉換為 UTC

在 Python 中,將本地時間的日期時間字串轉換為 UTC時間的字串涉及以下步驟:

  • 將輸入字串解析為簡單的日期時間物件: 刪除任何時區資訊以獲得沒有時區上下文的日期時間。
  • 識別本地時區: 使用pytz 模組確定適當的時區,該模組提供了完整的時間列表zone.
  • 構造時區物件:從本機建立時區類別的實例timezone。
  • 將時區附加到 naive datetime: 使用 localize() 方法為 naive datetime 物件設定時區。
  • 轉換 datetime到 UTC: 利用 astimezone()方法將日期時間從本地時區轉換為UTC.

範例程式碼:

from datetime import datetime
import pytz

# Given local time string
local_time_str = "2008-09-17 14:02:00"

# Local timezone
local_timezone = pytz.timezone("America/New_York")

# Parse local time string into naive datetime
naive_datetime = datetime.strptime(local_time_str, "%Y-%m-%d %H:%M:%S")

# Localize naive datetime with timezone
local_datetime = local_timezone.localize(naive_datetime)

# Convert to UTC
utc_datetime = local_datetime.astimezone(pytz.utc)

# Resultant UTC time string
utc_time_str = utc_datetime.strftime("%Y-%m-%d %H:%M:%S")

print(utc_time_str)  # Output: 2008-09-17 04:02:00

此程式碼片段演示了從本地時間(美國/紐約,UTC -5)到UTC 的轉換,產生UTC 時間的字串表示形式。

以上是如何在 Python 中將本機時間字串轉換為 UTC 時間字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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