Search code examples
pythonpython-2.7datetimetimezonepytz

How would I add the timezone to a datetime.datetime object?


I have a datetime.datetime object (datetime.datetime(2014, 4, 11, 18, 0)) and I would like to assign it a timezone using pytz. I know you can use pytz with a datetime.datetime.now() object (datetime.datetime.now(pytz.timezone('America/Los_Angeles'))) but how would I do it with a custom object?


Solution

  • Use the localize method:

    import pytz
    import datetime
    la = pytz.timezone('America/Los_Angeles')
    now = la.localize(datetime.datetime.now())
    print(repr(now))
    

    yields

    datetime.datetime(2014, 4, 11, 21, 36, 2, 981916, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
    

    localize is used to interpret timezone-unaware datetimes with respect to a timezone. The result is a timezone-aware datetime. Note that some timezone-unaware datetimes, such as datetime(2002, 10, 27, 1, 30, 00), are ambiguous in certain timezones. Use the is_dst parameter to avoid the ambiguity.

    astimezone is used to convert aware datetimes to other timezones.