Converting timezone-aware datetime to local time in Python Converting timezone-aware datetime to local time in Python python python

Converting timezone-aware datetime to local time in Python


In general, to convert an arbitrary timezone-aware datetime to a naive (local) datetime, I'd use the pytz module and astimezone to convert to local time, and replace to make the datetime naive:

In [76]: import pytzIn [77]: est=pytz.timezone('US/Eastern')In [78]: d.astimezone(est)Out[78]: datetime.datetime(2010, 10, 30, 13, 21, 12, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)In [79]: d.astimezone(est).replace(tzinfo=None)Out[79]: datetime.datetime(2010, 10, 30, 13, 21, 12)

But since your particular datetime seems to be in the UTC timezone, you could do this instead:

In [65]: dOut[65]: datetime.datetime(2010, 10, 30, 17, 21, 12, tzinfo=tzutc())In [66]: import datetimeIn [67]: import calendarIn [68]: datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple()))Out[68]: datetime.datetime(2010, 10, 30, 13, 21, 12)

By the way, you might be better off storing the datetimes as naive UTC datetimes instead of naive local datetimes. That way, your data is local-time agnostic, and you only convert to local-time or any other timezone when necessary. Sort of analogous to working in unicode as much as possible, and encoding only when necessary.

So if you agree that storing the datetimes in naive UTC is the best way, then all you'd need to do is define:

local_d = d.replace(tzinfo=None)


In recent versions of Django (at least 1.4.1):

from django.utils.timezone import localtimeresult = localtime(some_time_object)


A portable robust solution should use the tz database. To get local timezone as pytz tzinfo object, use tzlocal module:

#!/usr/bin/env pythonimport iso8601import tzlocal # $ pip install tzlocallocal_timezone = tzlocal.get_localzone()aware_dt = iso8601.parse_date("2010-10-30T17:21:12Z") # some aware datetime objectnaive_local_dt = aware_dt.astimezone(local_timezone).replace(tzinfo=None)

Note: it might be tempting to use something like:

#!/usr/bin/env python3# ...naive_local_dt = aware_dt.astimezone().replace(tzinfo=None)

but it may fail if the local timezone has a variable utc offset but python does not use a historical timezone database on a given platform.