
将 UTC 日期时间字符串转换为本地日期时间
问题:
如何转换 UTC日期时间字符串(以字符串形式存储在 App Engine 的 Bigtable 中)转换为最终用户的正确时区?
答案:
要将 UTC 日期时间字符串转换为用户正确时区的日期时间,可以使用 python-dateutil 库。该库在 zoneinfo (Olson) 数据库之上提供 tzinfo 实现,允许通过规范名称轻松引用时区规则。
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from datetime import datetime
from dateutil import tz
# Hardcode zones:
from_zone = tz.gettz( 'UTC' )
to_zone = tz.gettz( 'America/New_York' )
# Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# Create a datetime object from the UTC string
utc = datetime. strptime ( '2011-01-21 02:37:21' , '%Y-%m-%d %H:%M:%S' )
# Convert the datetime object to UTC timezone
utc = utc.replace(tzinfo=from_zone)
# Convert the datetime object to the user's timezone
local = utc.astimezone(to_zone)
|
登录后复制
时区的推荐存储信息:
-
“-5:00”或“EST”:此方法很简单,但有局限性,因为它假设用户时区的恒定偏移量。
-
规范名称:使用 Olson 数据库中的规范名称更加灵活,时区感知,因为它考虑了时区的历史变化。 python-dateutil 库允许通过规范名称引用时区。
例如,可以使用以下命令将“-5:00”转换为“America/New_York”:
1 2 3 | import pytz
est = pytz.timezone( "America/New_York" )
est_name = est.zone
|
登录后复制
以上是如何在 Python 中将 UTC 日期时间字符串转换为本地时区?的详细内容。更多信息请关注PHP中文网其他相关文章!