如何将 python 的 datetime.tzinfo 对象转换为钟摆的 Timezone 对象?

时间:2021-06-22 15:32:30

标签: python datetime pendulum

我知道我可以将 datetime.datetime 转换为钟摆

from datetime import datetime,timezone
import pendulum

a = datetime(2021,6,1,tzinfo=timezone.utc)
b = pendulum.instance(a)
b.tzinfo.name # the presence of the attribute 'name' means it's a pendulum timezone
type(b.tzinfo) # pendulum.tz.timezone.FixedTimezone

但我有一个独立的 datetime.tzinfo ,是否可以将其转换为 pendulum.tz.timezone.*

a = timezone.utc # well, imagine that it can be any tzinfo
b = pendulum.xxxxx(a) # that gives tome pendum.tz.timezone class

有这种方法吗?

1 个答案:

答案 0 :(得分:0)

查看 pendulum.instance() 的实现,您可以看出它依赖于“私有”函数 _safe_timezone,您可以使用该函数将 tzinfo 转换为钟摆的时区。以 _ 下划线开头的方法/函数通常表示它们不构成公共 API 的一部分,但函数在那里。

tzinfo=timezone.utc 的情况下,pendulum.instance() 会将 tzinfo 对象转换为以小时为单位的偏移量并将其传递给 pendulum.datetime,后者将使用 pendulum._safe_timezone() 将其转换为pendulum.tz.timezone.FixedTimeZone。但 _safe_timezone() 也接受常规 datetime.tzinfo 作为输入。

a = pendulum._safe_timezone(timezone.utc) #  Timezone('UTC')
type(a) # pendulum.tz.timezone.FixedTimezone
相关问题