简体   繁体   English

将具有 UTC 时区偏移量的日期转换为相应的本地时区格式

[英]Convert a date with UTC timezone offset to corresponding local timezone format

I have a string date which already contains appropriate timezone offset -08:00 and I can convert it into a datetime variable but with UTC timezone format我有一个字符串日期,它已经包含适当的时区偏移 -08:00,我可以将其转换为日期时间变量,但使用 UTC 时区格式

from datetime import datetime
from pytz import timezone
import pytz

str_date = '2020-01-01T00:00:00-08:00'#
specific_date_format = "%Y-%m-%d %H:%M:%S %Z"

my_date = datetime.fromisoformat(str_date)
print(my_date.strftime(specific_date_format))

_____________________________________________
Output
>> 2020-01-01 00:00:00 UTC-08:00

Format I need is我需要的格式是

2020-01-01 00:00:00 PST

Not sure how to convert UTC-08:00 into PST.不确定如何将 UTC-08:00 转换为 PST。

Tried with pytz and saw suggestions to replace timezone with predefined 'America/Los_Angeles', but I need the code to detect that the hour offset UTC-08:00 corresponds to 'America/Los_Angeles' timezone and convert it as such.尝试使用 pytz 并看到用预定义的“America/Los_Angeles”替换时区的建议,但我需要代码来检测小时偏移 UTC-08:00 对应于“America/Los_Angeles”时区并将其转换为这样。

since your input already contains a UTC offset, you can parse the iso-format string to aware datetime (tzinfo set) and use astimezone to set the correct time zone.由于您的输入已经包含 UTC 偏移量,您可以解析 iso 格式字符串以了解日期时间(tzinfo 集)并使用astimezone设置正确的时区。 Using pytz:使用 pytz:

from datetime import datetime
from pytz import timezone # Python 3.9: zoneinfo (standard lib)

str_date = '2020-01-01T00:00:00-08:00'

# to datetime
dt = datetime.fromisoformat(str_date)

# to tz
dt_tz = dt.astimezone(timezone("America/Los_Angeles"))

print(dt_tz)
# 2020-01-01 00:00:00-08:00
print(repr(dt_tz))
# datetime.datetime(2020, 1, 1, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
print(dt_tz.strftime("%a, %d %b %Y %H:%M:%S %Z"))
# Wed, 01 Jan 2020 00:00:00 PST

See also: Display the time in a different time zone - eg this answer for a Python 3.9/zoneinfo example.另请参阅:显示不同时区的时间- 例如 Python 3.9/zoneinfo 示例的此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM