Categories
Python Answers

How to convert UTC datetime string to local datetime with Python?

Spread the love

Sometimes, we want to convert UTC datetime string to local datetime with Python.

In this article, we’ll look at how to convert UTC datetime string to local datetime with Python.

How to convert UTC datetime string to local datetime with Python?

To convert UTC datetime string to local datetime with Python, we can call the fromtimestamp and utcfromtimestamp methods.

For instance, we write

from datetime import datetime
import time

def datetime_from_utc_to_local(utc_datetime):
    now_timestamp = time.time()
    offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)
    return utc_datetime + offset

to create the datetime_from_utc_to_local function that takes the utc_datetime value.

In it, we get the local time offset from UTC with

offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)

Then we add the offset to the utc_datetime and return the sum to get the local time.

Conclusion

To convert UTC datetime string to local datetime with Python, we can call the fromtimestamp and utcfromtimestamp methods.

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 *