Converting UTC Datetime to Local Datetime Using Standard Library
Converting a UTC datetime instance to a local datetime can be done using the standard library in Python. A common solution is to use the astimezone method, but it requires providing a timezone object. Here are alternative approaches using only the standard library:
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:
<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) assert utc_dt.resolution >= timedelta(microseconds=1) return local_dt.replace(microsecond=utc_dt.microsecond)</code>
Using pytz (Python 2/3):
<code class="python">import pytz local_tz = pytz.timezone('Europe/Moscow') # Provide your local timezone name def utc_to_local(utc_dt): local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) return local_tz.normalize(local_dt)</code>
Example:
<code class="python">def aslocaltimestr(utc_dt): return utc_to_local(utc_dt).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z') utc_dt = datetime(2010, 6, 6, 17, 29, 7, 730000) print(aslocaltimestr(utc_dt))</code>
This will print the local datetime string based on the default timezone.
Note: The default timezone is not always reliable and may vary based on system settings. For more reliable and cross-platform results, it is recommended to specify the local timezone explicitly.
The above is the detailed content of How to Convert UTC Datetime to Local Datetime in Python Using the Standard Library?. For more information, please follow other related articles on the PHP Chinese website!