How to check if a datetime object is localized with pytz?

前端 未结 4 856
你的背包
你的背包 2020-12-05 03:42

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

4条回答
  •  一生所求
    2020-12-05 04:32

    How do I determine if localization is needed?

    From datetime docs:

    • a datetime object d is aware iff:

      d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None
      
    • d is naive iff:

      d.tzinfo is None or d.tzinfo.utcoffset(d) is None
      

    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)
    

    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 use tz.localize() method).

提交回复
热议问题