繁体   English   中英

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

[英]How to convert a python's datetime.tzinfo object to a pendulum's Timezone object?

我知道我可以将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

有这样的方法吗?

查看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

暂无
暂无

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

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