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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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.