將本地時間字串轉換為 UTC
在 Python 中,將本地時間的日期時間字串轉換為 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中文網其他相關文章!