How to check if a datetime object is localized with pytz?(如何检查日期时间对象是否使用 pytz 本地化?)
问题描述
我想存储一个具有本地化 UTC 时区的日期时间对象.可以给存储 datetime 对象的方法一个非本地化的 datetime (naive) 对象或已经本地化的对象.如何确定是否需要本地化?
I want to store a datetime object with a localized UTC timezone. The method that stores the datetime object can be given a non-localized datetime (naive) object or an object that already has been localized. How do I determine if localization is needed?
缺少 if 条件的代码:
Code with missing if condition:
class MyClass:
def set_date(self, d):
# what do i check here?
# if(d.tzinfo):
self.date = d.astimezone(pytz.utc)
# else:
self.date = pytz.utc.localize(d)
推荐答案
如何确定是否需要本地化?
How do I determine if localization is needed?
来自 <代码>日期时间文档:
一个日期时间对象
d
知道 iff:
d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None
d
是幼稚的 iff:
d.tzinfo is None or d.tzinfo.utcoffset(d) is None
虽然如果 d
是表示 UTC 时区时间的日期时间对象,那么您可以在这两种情况下使用:
Though if d
is a datetime object representing time in UTC timezone then you could use in both cases:
self.date = d.replace(tzinfo=pytz.utc)
无论 d
是时区感知还是幼稚,它都能正常工作.
It works regardless d
is timezone-aware or naive.
注意:不要使用带有非固定时区的 datetime.replace()
方法UTC 偏移量(可以将其与 UTC 时区一起使用,否则应使用 tz.localize()
方法).
Note: don't use datetime.replace()
method with a timezone with a non-fixed utc offset (it is ok to use it with UTC timezone but otherwise you should use tz.localize()
method).
这篇关于如何检查日期时间对象是否使用 pytz 本地化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查日期时间对象是否使用 pytz 本地化?


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01