【问题标题】:How can I convert a half-hour timezone to a pytz timezone object?如何将半小时时区转换为 pytz 时区对象?
【发布时间】:2015-10-05 07:28:28
【问题描述】:

我正在尝试读取其时区由其 UTC 偏移量指定的时间,并将它们存储为 python 日期时间。

pytz 模块提供了可用的时区,我认为完整的列表在this question 中给出。如果是这样,大部分时间可以通过使用对应的Etc/时区并翻转符号来存储:

Etc/GMT
Etc/GMT+0
Etc/GMT+1
Etc/GMT+10
Etc/GMT+11
Etc/GMT+12
Etc/GMT+2
Etc/GMT+3
Etc/GMT+4
Etc/GMT+5
Etc/GMT+6
Etc/GMT+7
Etc/GMT+8
Etc/GMT+9
Etc/GMT-0
Etc/GMT-1
Etc/GMT-10
Etc/GMT-11
Etc/GMT-12
Etc/GMT-13
Etc/GMT-14
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
Etc/GMT-8
Etc/GMT-9

但是,纽芬兰标准时间和阿富汗时间等一些时区与 GMT 有半小时的偏移(分别为-3:30 和 +4:30)。如何在不手动将这些特定偏移量映射到America/St_JohnsAsia/Kabul 的情况下将这些时间与其适当的时区一起存储?

【问题讨论】:

  • 所以你不想使用pytz.timezone("Canada/Newfoundland")之类的东西?
  • 我宁愿不要。数据以 GMT 偏移量给出,因此我必须手动设置每个偏移量到正确城市的映射。不是一件大事,但似乎应该有一种不需要地理知识的方法。

标签: python datetime python-3.x pytz


【解决方案1】:

oyu 可以做一些事情,虽然不是你想要的。

>>> nf_offset = pytz.FixedOffset(-150) # offset is in minutes, so 150=2.5 hours
>>> nf_tz = pytz.datetime("Canada/Newfoundland")
>>> datetime.now(nf_tz).strftime("%H:%M") == datetime.now(nf_offset).strftime("%H:%M")
True

它们是不同的对象,因此在此之后不确定您是否可以做您希望的事情,但这将为您提供一个通用对象,您可以从中比较与 UTC 的任意偏移量的时间。

【讨论】:

    【解决方案2】:

    不要使用Etc/GMT±h POSIX 时区。 They are present only for historical reasons (and perhaps for ships in the sea).

    一般而言,UTC 偏移量不足以指定时区,即同一时区在不同时间可能有不同的 utc 偏移量。反过来,多个时区可能在某个时间点具有相同的 UTC 偏移量。

    如果给你一个固定的 UTC 偏移量 对应的日期,那么你可以使用any FixedOffset implementation

    如果您想获得其他日期的正确时间,则必须将输入数据映射到正确的时区 ID,例如 'America/St_Johns'。见pytz: return Olson Timezone name from only a GMT Offset

    【讨论】:

      猜你喜欢
      • 2018-01-03
      • 2016-02-05
      • 2014-10-05
      • 2012-08-29
      • 2022-01-11
      • 1970-01-01
      • 2019-06-19
      • 2017-05-13
      • 2015-12-09
      相关资源
      最近更新 更多