How to make an unaware datetime timezone aware in python

前端 未结 12 2323
一向
一向 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 08:50

    All of these examples use an external module, but you can achieve the same result using just the datetime module, as also presented in this SO answer:

    from datetime import datetime
    from datetime import timezone
    
    dt = datetime.now()
    dt.replace(tzinfo=timezone.utc)
    
    print(dt.replace(tzinfo=timezone.utc).isoformat())
    '2017-01-12T22:11:31+00:00'
    

    Fewer dependencies and no pytz issues.

    NOTE: If you wish to use this with python3 and python2, you can use this as well for the timezone import (hardcoded for UTC):

    try:
        from datetime import timezone
        utc = timezone.utc
    except ImportError:
        #Hi there python2 user
        class UTC(tzinfo):
            def utcoffset(self, dt):
                return timedelta(0)
            def tzname(self, dt):
                return "UTC"
            def dst(self, dt):
                return timedelta(0)
        utc = UTC()
    

提交回复
热议问题