Home > Article > Backend Development > How to Convert a UTC Datetime to a Local Datetime in Python Using the Standard Library?
In programming, it is often necessary to convert datetimes between different time zones. The standard Python library provides limited functionality for this, but it is possible to achieve a basic conversion without external dependencies.
Given a UTC datetime instance created with datetime.utcnow(), how can we convert it to a local datetime instance, using only the Python standard library? Additionally, how do we obtain the default local timezone?
Python 3.3 :
<code class="python">from datetime import datetime, timezone def utc_to_local(utc_dt): return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)</code>
Python 2/3 (using integer timestamp):
<code class="python">import calendar from datetime import datetime, timedelta def utc_to_local(utc_dt): timestamp = calendar.timegm(utc_dt.timetuple()) local_dt = datetime.fromtimestamp(timestamp) return local_dt.replace(microsecond=utc_dt.microsecond)</code>
Python 2/3 (with pytz dependency):
<code class="python">import pytz local_tz = pytz.timezone('Europe/Moscow') # use local timezone name here def utc_to_local(utc_dt): local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) return local_tz.normalize(local_dt)</code>
<code class="python">def aslocaltimestr(utc_dt): return utc_to_local(utc_dt).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z') print(aslocaltimestr(datetime(2010, 6, 6, 17, 29, 7, 730000))) print(aslocaltimestr(datetime(2010, 12, 6, 17, 29, 7, 730000))) print(aslocaltimestr(datetime.utcnow()))</code>
2010-06-06 21:29:07.730000 MSD+0400 2010-12-06 20:29:07.730000 MSK+0300 2012-11-08 14:19:50.093745 MSK+0400
The above is the detailed content of How to Convert a UTC Datetime to a Local Datetime in Python Using the Standard Library?. For more information, please follow other related articles on the PHP Chinese website!