When dealing with international user base you would find yourself in the need of date time conversion from one time zone to another. Unfortunately it's one of the cumbersome task and inbuilt support of datetime
module is not sufficient but fortunately Python has external library called pytz
to take care of date time conversion.
Install Pytz using pip
pip install pytz
General Steps for Date Time Conversion
- Create Python Date Time Object.
- Create Pytz Time Zone Object for the Source Time Zone.
- Assign Source Time Zone to Created Date Time Object.
- Create Pytz Time Zone Object for the Target Time Zone.
- Convert Source Time Zone to Target Time Zone.
Example - Time Zone Conversion with Pytz
In below example we will convert current date time which is in time zone US Eastern (EST) to target timezone Moscow Standard Time (MSK).
- Get current Date Time Object as Source Date using Python's
datetime
module. - Create Source Time Zone Object using
pytz.timezone
. - Assign Source Time Zone to Created Date Time Object using
localize
method ofpytz.timezone
. - Create Target Time Zone Object using
pytz.timezone
. - Convert Source Time Zone to Target Time Zone using
astimezone
method ofpytz.timezone
.
import datetime
import pytz
source_date = datetime.datetime.now()
print source_date
2018-05-17 17:11:00.461000
source_time_zone = pytz.timezone('US/Eastern')
print source_time_zone
US/Eastern
source_date_with_timezone = source_time_zone.localize(source_date)
print source_date_with_timezone
2018-05-17 17:11:00.461000-04:00
target_time_zone = pytz.timezone('Europe/Moscow')
print target_time_zone
Europe/Moscow
target_date_with_timezone = source_date_with_timezone.astimezone(target_time_zone)
print target_date_with_timezone
2018-05-18 00:11:00.461000+03:00
Miscellaneous
- Refer
pytz.all_timezones
to get complete list of Time Zones available insidepytz
. - Note that when you use
localize
method ofpytz.timezone
it takes care of day light savings adjustment. - If you do not want day light savings adjustment then please modify
tzinfo
attribute of source date by usingreplace
method of datetime object.
source_date_with_timezone = source_date.replace(tzinfo=source_time_zone)
- To convert date into string use
strftime
ofdatetime
object.target_date_with_timezone.strftime('%Y-%m-%d %H:%M')
- To convert string formatted time to python datetime object use
strptime
ofdatetime
module.