How to make an unaware datetime timezone aware in python

前端 未结 12 2307
一向
一向 2020-11-22 08:39

What I need to do

I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezon

12条回答
  •  半阙折子戏
    2020-11-22 09:09

    This codifies @Sérgio and @unutbu's answers. It will "just work" with either a pytz.timezone object or an IANA Time Zone string.

    def make_tz_aware(dt, tz='UTC', is_dst=None):
        """Add timezone information to a datetime object, only if it is naive."""
        tz = dt.tzinfo or tz
        try:
            tz = pytz.timezone(tz)
        except AttributeError:
            pass
        return tz.localize(dt, is_dst=is_dst) 
    

    This seems like what datetime.localize() (or .inform() or .awarify()) should do, accept both strings and timezone objects for the tz argument and default to UTC if no time zone is specified.

提交回复
热议问题