从Python中的时区名称获取UTC偏移


71

如何从python中的时区名称获取UTC偏移量?

例如:我有Asia/Jerusalem,我想得到+0200

Answers:


106

由于采用DST(夏令时),结果取决于一年中的时间:

import datetime, pytz

datetime.datetime.now(pytz.timezone('Asia/Jerusalem')).strftime('%z')

# returns '+0300' (because 'now' they have DST)


pytz.timezone('Asia/Jerusalem').localize(datetime.datetime(2011,1,1)).strftime('%z')

# returns '+0200' (because in January they didn't have DST)

59

您是否尝试过使用pytz项目和utcoffset方法?

例如

>>> import datetime
>>> import pytz
>>> pacific_now = datetime.datetime.now(pytz.timezone('US/Pacific'))
>>> pacific_now.utcoffset().total_seconds()/60/60
-7.0

2
顺便说一句,pytz的Ubuntu软件包是python-tz。
— Randall Cook

1
我不敢对他投反对票,但据我所知,utcoffset是一种针对日期时间对象的方法,因此它不提供时区名称。
— 汤姆(Tom)

1
@Tom:虽然它也适用于tzinfo对象。参见pytz.sourceforge.net/#tzinfo-api
— Jon Skeet

1
@ jon-skeet谢谢,我错过了。我们现在正式加强吗?
— 汤姆(Tom)

2
请注意,如果服务器使用的时区不是给定的时区,则在夏令时切换期间会产生错误的结果。timezone.utcoffset()假定传递给的datetime在该时区本地,并且如果传递的夏令时开始或结束的那一小时将失败。datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Pacific')).utcoffset().total_seconds() / 60 / 60是更好的方法。
— 内森·维莱克斯库萨

2

从python datetime对象转换为UTC时间戳时,我遇到了类似的问题。我的日期时间与时区无关(非常幼稚),因此astimezone无法正常工作。

为了缓解此问题,我使我的datetime对象时区变得可识别,然后使用了上述魔术。

import pytz
system_tz = pytz.timezone(constants.TIME_ZONE)
localized_time = system_tz.localize(time_of_meeting)
fmt = "%Y%m%dT%H%M%S" + 'Z'
return localized_time.astimezone(pytz.utc).strftime(fmt)

这里, constants.TIME_ZONE我有了持久对象的默认时区。

希望这对尝试将python datetime对象转换为UTC的人有所帮助。转换后,请以任何方式格式化。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.