unexpected results converting timezones in python

前端 未结 5 1982
谎友^
谎友^ 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:57

    Unfortunately, creating timezone aware dates using this method doesn't work.

    If you are using Django, they have a utility function, make_aware, that does this correctly.

    from django.utils.timezone import make_aware
    from pytz import timezone
    
    unaware_datetime = datetime(2007, 12, 5)
    local_datetime = make_aware(datetime(2007, 12, 5))
    specific_datetime = make_aware(datetime(2007, 12, 5), timezone("Australia/Melbourne"))
    

    If you're not using Django, then the source code for the make_aware function may give you inspiration.

提交回复
热议问题