Converting UTC Datetime to Local Datetime Using Python Standard Library
When dealing with datetime objects, it is often necessary to convert between UTC (Coordinated Universal Time) and local time. The Python standard library provides built-in functionality to accomplish this.
pytz Alternative for Python 3.3
In Python 3.3 and above, the timezone module simplifies the conversion process:
<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>
Solution for Python 2/3
For Python 2 and 3, an alternative approach is to use calendar.timegm and datetime.fromtimestamp:
<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>
Example Usage
To illustrate the conversion, consider the following example:
<code class="python">from datetime import datetime utc_dt = datetime(2023, 7, 18, 12, 0, 0, tzinfo=timezone.utc) local_dt = utc_to_local(utc_dt) print(local_dt)</code>
Output:
2023-07-18 18:00:00.000000+06:00
Note for DateTime with No Microsecond Resolution
In cases where the UTC datetime has no microsecond resolution, the astimezone method may introduce microsecond values that are not present in the original datetime. To ensure precision, use the alternative method provided for Python 2/3.
Handling DST Changes
Both solutions take into account daylight saving time (DST) changes and correctly convert UTC datetime to the appropriate local time with DST applied or removed as needed.
The above is the detailed content of How to Convert UTC Datetime to Local Datetime Using Python Standard Library?. For more information, please follow other related articles on the PHP Chinese website!