如何检查日期时间对象是否使用 pytz 本地化?
我想存储具有本地化 UTC 时区的日期时间对象。可以为存储日期时间对象的方法提供一个非本地化的日期时间(原始)对象或已本地化的对象。如何判断是否需要本地化?
缺少 if 条件的代码:
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)
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?
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果要检查日期时间对象“d”是否已本地化,请检查 d.tzinfo,如果为 None,则没有本地化。
if you want to check if a datetime object 'd' is localized, check the d.tzinfo, if it is None, no localization.
这是一个总结最佳答案的函数。
Here is a function wrapping up the top answer.
这是一个更完整的函数,用于将时间戳 obj 转换或强制为 utc。如果出现异常,则意味着时间戳未本地化。由于在代码中始终使用 UTC 工作是一种很好的做法,因此此函数对于持久性的入门级非常有用。
JF Sebastian 的答案中“try catch”的一个小补充是附加的 catch 条件,没有它,函数不会捕获所有幼稚的情况。
Here's a more complete function to convert or coerce a timestamp obj to utc. If it reaches the exception this means the timestamp is not localized. Since it's good practice to always work in UTC within the code, this function is very useful at the entry level from persistence.
The small addition from the 'try catch' in the answer by J.F. Sebastian is the additional catch condition, without which not all naive cases will be caught by the function.
来自
日期时间
文档:日期时间对象
d
是已知的当且仅当:d
是天真的 iff:尽管如果
d
是表示 UTC 时区时间的日期时间对象,那么您可以在两种情况下使用:无论如何它都有效
d
是时区感知的或天真的。注意:不要将
datetime.replace()
方法与具有非固定 utc 偏移量的时区一起使用< /a> (可以将其与 UTC 时区一起使用,但否则您应该使用tz.localize()
方法)。From
datetime
docs:a datetime object
d
is aware iff:d
is naive iff:Though if
d
is a datetime object representing time in UTC timezone then you could use in both cases:It works regardless
d
is timezone-aware or naive.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 usetz.localize()
method).