everyday

Python - Time Module - Setting Timezones

The default time zone for a program is taken from the system clock time. But, we can also set time zones in environment variable using by using TZ. For more on environment variables, please refer to the link.

Below snippet demonstrates the capability of setting different time zones which can useful when you have data coming in from parts of world and you have to change the time zones based on the data attributes.

#time_timezone.py

import time
import os


def show_zone_info():
    print('  TZ    :', os.environ.get('TZ', '(not set)'))
    print('  tzname:', time.tzname)
    print('  Zone  : {} ({})'.format(
        time.timezone, (time.timezone / 3600)))
    print('  DST   :', time.daylight)
    print('  Time  :', time.ctime())
    print()


print('Default :')
show_zone_info()

ZONES = [
    'GMT',
    'Europe/Amsterdam',
]

for zone in ZONES:
    os.environ['TZ'] = zone
    time.tzset()
    print(zone, ':')
    show_zone_info()
$ python3 time_timezone.py

Default :
  TZ    : (not set)
  tzname: ('EST', 'EDT')
  Zone  : 18000 (5.0)
  DST   : 1
  Time  : Sun Dec  9 12:43:53 2018

GMT :
  TZ    : GMT
  tzname: ('GMT', 'GMT')
  Zone  : 0 (0.0)
  DST   : 0
  Time  : Sun Dec  9 17:43:53 2018

Europe/Amsterdam :
  TZ    : Europe/Amsterdam
  tzname: ('CET', 'CEST')
  Zone  : -3600 (-1.0)
  DST   : 1
  Time  : Sun Dec  9 18:43:53 2018

This is part of series of articles from Python Module of the Week

#pymotw

- 1 toast