Understand DateTime converting on python

Pham Ngoc Quy
Dec 22, 2020


Have ever you confusing when converting the timezone on python.

So, in this post, I will describe a simple way to understand and using timezone converting.

We have two steps to conversion DateTime from a timezone to another timezone.
1. Determined current timezone.

from datetime import datetime
fdate = datetime.now()

For the above code, the fdate variable will be assign timezone of local. I’m in Singapore fdate is in Singapore UTC+8.

To assign a DateTime to specify local timezone:

import pytz
us_moscow_time_zone = pytz.timezone('Europe/Moscow')
fdate = us_moscow_time_zone.localize(fdate)

Now, change the timezone of fdate

utc_time_zone = pytz.timezone('UTC')
fdate = fdate.astimezone(utc_time_zone)