Tech Monger

Programming, Web Development and Computer Science.

Skip to main content| Skip to information by topic

Pytz - Date Time Conversion Across Time Zones in Python

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 datetimemodule 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

  1. Create Python Date Time Object.
  2. Create Pytz Time Zone Object for the Source Time Zone.
  3. Assign Source Time Zone to Created Date Time Object.
  4. Create Pytz Time Zone Object for the Target Time Zone.
  5. 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).

  1. Get current Date Time Object as Source Date using Python's datetime module.
  2. import datetime
    import pytz
    source_date = datetime.datetime.now()
    print source_date
    
    2018-05-17 17:11:00.461000
    
  3. Create Source Time Zone Object using pytz.timezone.
  4. source_time_zone = pytz.timezone('US/Eastern')
    print source_time_zone
    
    US/Eastern
    
  5. Assign Source Time Zone to Created Date Time Object using localize method of pytz.timezone.
  6. source_date_with_timezone = source_time_zone.localize(source_date)
    print source_date_with_timezone
    
    2018-05-17 17:11:00.461000-04:00
    
  7. Create Target Time Zone Object using pytz.timezone.
  8. target_time_zone = pytz.timezone('Europe/Moscow')
    print target_time_zone
    
    Europe/Moscow
    
  9. Convert Source Time Zone to Target Time Zone using astimezone method of pytz.timezone.
  10. 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 inside pytz.
  • Note that when you use localize method of pytz.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 using replace method of datetime object.
    source_date_with_timezone = source_date.replace(tzinfo=source_time_zone)
  • To convert date into string use strftime of datetime object.
    target_date_with_timezone.strftime('%Y-%m-%d %H:%M')
    
  • To convert string formatted time to python datetime object use strptime of datetime module.

Tagged Under : Open Source Python