Convert UTC to local timezone – Python

Here’s how you can get the date and time in UTC and convert it to user’s local timezone in Python.

from fastapi import FastAPI
from datetime import datetime, timezone as timezone_module
from dateutil import tz

app = FastAPI()

utc = datetime.now(timezone_module.utc)

# Hardcode zones:
from_zone = tz.gettz("UTC")
to_zone = tz.gettz("Asia/Karachi")

# you can get user's local timezone in Javascript using following code:
# Intl.DateTimeFormat().resolvedOptions().timeZone

# Tell the datetime object that it's in UTC time zone since 
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
local = utc.astimezone(to_zone)

# get in readable format
local = local.strftime("%b %d, %Y %H:%M:%S")

print(local)

Comments has been added with each line for explanation. You can check its real-world example in a URL shortener app we created in Python.