Understand DateTime converting on python

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)

--

--

Dev-Ops, Data Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store