Home > Backend Development > Python Tutorial > How to Convert UTC Datetime to Local Datetime Using Python Standard Library?

How to Convert UTC Datetime to Local Datetime Using Python Standard Library?

Mary-Kate Olsen
Release: 2024-11-03 09:02:02
Original
373 people have browsed it

How to Convert UTC Datetime to Local Datetime Using Python Standard Library?

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>
Copy after login

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>
Copy after login

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>
Copy after login

Output:

2023-07-18 18:00:00.000000+06:00
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template