Categories
Python Answers

How to convert a UTC datetime to a local datetime using only standard library with Python?

Spread the love

Sometimes, we want to convert a UTC datetime to a local datetime using only standard library with Python.

In this article, we’ll look at how to convert a UTC datetime to a local datetime using only standard library with Python.

How to convert a UTC datetime to a local datetime using only standard library with Python?

To convert a UTC datetime to a local datetime using only standard library with Python, we can use the pytz module.

For instance, we write

import pytz

local_tz = pytz.timezone('Europe/London')


def utc_to_local(utc_dt):
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_tz.normalize(local_dt)

to create the utc_to_local function that takes the utc_dt datetime.

In it, we call utc_dt.replace with the tzinfo argument set to pytz.utc to parse the datetime as UTC.

Then we call astimezone with local_tz to convert the UTC datetime to the local_tz time zone.

And then we call local_tz.normalize with the local_dt to return the local datetime.

Conclusion

To convert a UTC datetime to a local datetime using only standard library with Python, we can use the pytz module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *