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

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

Susan Sarandon
Release: 2024-11-03 06:00:04
Original
702 people have browsed it

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

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

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

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

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

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!

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