How to make an unaware datetime timezone aware in python

前端 未结 12 2215
一向
一向 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:04

    Use dateutil.tz.tzlocal() to get the timezone in your usage of datetime.datetime.now() and datetime.datetime.astimezone():

    from datetime import datetime
    from dateutil import tz
    
    unlocalisedDatetime = datetime.now()
    
    localisedDatetime1 = datetime.now(tz = tz.tzlocal())
    localisedDatetime2 = datetime(2017, 6, 24, 12, 24, 36, tz.tzlocal())
    localisedDatetime3 = unlocalisedDatetime.astimezone(tz = tz.tzlocal())
    localisedDatetime4 = unlocalisedDatetime.replace(tzinfo = tz.tzlocal())
    

    Note that datetime.astimezone will first convert your datetime object to UTC then into the timezone, which is the same as calling datetime.replace with the original timezone information being None.

提交回复
热议问题