How to make a timezone aware datetime object in Python? How to make a timezone aware datetime object in Python? python python

How to make a timezone aware datetime object in Python?


In general, to make a naive datetime timezone-aware, use the localize method:

import datetimeimport pytzunaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)now_aware = pytz.utc.localize(unaware)assert aware == now_aware

For the UTC timezone, it is not really necessary to use localize since there is no daylight savings time calculation to handle:

now_aware = unaware.replace(tzinfo=pytz.UTC)

works. (.replace returns a new datetime; it does not modify unaware.)


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, timezonedt = datetime.now()dt = dt.replace(tzinfo=timezone.utc)print(dt.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.utcexcept 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()


I wrote this at Nov 22 2011 , is Pyhton 2 only , never checked if it work on Python 3

I had use from dt_aware to dt_unaware

dt_unaware = dt_aware.replace(tzinfo=None)

and dt_unware to dt_aware

from pytz import timezonelocaltz = timezone('Europe/Lisbon')dt_aware = localtz.localize(dt_unware)

but answer before is also a good solution.