unexpected results converting timezones in python

前端 未结 5 1990
谎友^
谎友^ 2020-11-27 17:27

I\'m trying to understand why I\'m getting these results when converting timezones to UTC:

In [74]: d1 = datetime(2007, 12, 5, 6, 30,tzinfo=pytz.timezone(\'U         


        
5条回答
  •  半阙折子戏
    2020-11-27 17:49

    What I got is just a workaround, the simple rule is Never create datetime with timezone info by using datetime().

    This sample would give you a hint for this. As you see, you could avoid the unexpected difference, once and only you make "naive" datetime (it is, datetime without timezone info) and then localize it (it is not applied when you create datetime on UTC though) :

    import pytz
    from datetime import datetime
    
    # make Jan 1 on PDT -> UTC
    pdt = pytz.timezone("America/Los_Angeles")
    pdtnow1 = datetime(2014,1,1, tzinfo=pdt)
    pdtnow2 = pdt.localize(datetime(2014,1,1))
    pytz.utc.normalize(pdtnow1)
    # > datetime.datetime(2014, 1, 1, 7, 53, tzinfo=)
    pytz.utc.normalize(pdtnow2)
    # > datetime.datetime(2014, 1, 1, 8, 0, tzinfo=)
    
    # make Jan 1 on UTC -> PDT
    utcnow1 = datetime(2014,1,1, tzinfo=pytz.utc)
    utcnow2 = pytz.utc.localize(datetime(2014,1,1))
    pdt.normalize(utcnow1)
    # > datetime.datetime(2013, 12, 31, 16, 0, 
    # > tzinfo=)
    pdt.normalize(utcnow2)
    # > datetime.datetime(2013, 12, 31, 16, 0, 
    # > tzinfo=)
    

提交回复
热议问题