如何检查datetime对象是否使用pytz进行本地化? [英] How to check if a datetime object is localized with pytz?

查看:124
本文介绍了如何检查datetime对象是否使用pytz进行本地化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想存储具有本地化UTC时区的datetime对象。存储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?

代码缺少条件:

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?

datetime docs

From datetime docs:


  • 一个datetime对象 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
    


  • code> d 是表示UTC时区的时间的datetime对象,那么您可以在以下两种情况下使用:

    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)
    

    它工作reg ardless d 是时区感知或天真的。

    It works regardless d is timezone-aware or naive.

    注意:不要使用带有非固定utc偏移的时区的 datetime.replace()方法(这是可以的要使用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).

    如果你想支持任意时区用于感知日期时间对象,即只需要天真的datetime对象来表示应用程序中UTC时区的时间,那么您可以使用 EAFP方法 d 转换为 pytz.utc timezone:

    If you want to support arbitrary timezones for aware datetime objects i.e., only naive datetime objects are required to represent time in UTC timezone in your application then you could use EAFP method to convert d to pytz.utc timezone:

    try:
        self.date = d.astimezone(pytz.utc) # aware object can be in any timezone
    except ValueError: # naive
        self.date = d.replace(tzinfo=pytz.utc) # d must be in UTC
    

    注意:在 d之后,您不需要调用 tz.normalize()方法。 astimezone()这里是因为目的地时区是UTC。

    Note: you don't need to call tz.normalize() method after d.astimezone() here because the destination timezone is UTC.

    即使 d.tzinfo 使用非pytz时区。

    It works even if d.tzinfo uses non-pytz timezones.

    这篇关于如何检查datetime对象是否使用pytz进行本地化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆