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

Linda Hamilton
Release: 2024-11-02 03:43:30
Original
937 people have browsed it

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

Converting UTC Datetime to Local Datetime Using Python 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.

Problem

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?

Solution

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

Using pytz (Optional)**

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>
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')

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

Output

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

Notes

  • Non-pytz solutions may not work on Windows.
  • The provided examples take into account Daylight Saving Time and recent UTC offset changes for MSK timezone.

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!