w3resource

Python: Get different time values with components of different timezones

Python Operating System Services: Exercise-21 with Solution

Write a Python program to get different time values with components timezone, timezone abbreviations, the offset of the local (non-DST) timezone, DST timezone and time of different timezones.

Sample Solution:

Python Code :

import time
import os
def zone_info():
   print('TZ   :', os.environ.get('TZ', '(not set)'))
   print('Timezone abbreviations:', time.tzname)
   print('Timezone : {} ({})'.format(
       time.timezone, (time.timezone / 3600)))
   print('DST timezone ', time.daylight)
   print('Time :', time.strftime('%X %x %Z'),'\n')
print('Default Zone:')
zone_info()
TIME_ZONES = [
   'Pacific/Auckland',
   'Europe/Berlin',
   'America/Detroit',
   'Singapore',
]
for zone in TIME_ZONES:
   os.environ['TZ'] = zone
   time.tzset()
   print(zone, ':')
   zone_info()

Sample Output:

Default Zone:
TZ   : (not set)
Timezone abbreviations: ('UTC', 'UTC')
Timezone : 0 (0.0)
DST timezone  0
Time : 12:05:33 01/20/20 UTC 

Pacific/Auckland :
TZ   : Pacific/Auckland
Timezone abbreviations: ('NZST', 'NZDT')
Timezone : -43200 (-12.0)
DST timezone  1
Time : 01:05:33 01/21/20 NZDT 

Europe/Berlin :
TZ   : Europe/Berlin
Timezone abbreviations: ('CET', 'CEST')
Timezone : -3600 (-1.0)
DST timezone  1
Time : 13:05:33 01/20/20 CET 

America/Detroit :
TZ   : America/Detroit
Timezone abbreviations: ('EST', 'EDT')
Timezone : 18000 (5.0)
DST timezone  1
Time : 07:05:33 01/20/20 EST 

Singapore :
TZ   : Singapore
Timezone abbreviations: ('+08', '+08')
Timezone : -28800 (-8.0)
DST timezone  0
Time : 20:05:33 01/20/20 +08

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get time values with components using local time and gmtime.
Next: Write a Python program that can suspend execution of a given script a given number of seconds.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Unpack a Tuple

>>> items = (0, 'b', 'one', 10,  11, 'zero')
>>> a, b, c, d, e, f = items
>>> print(f)
zero
>>> a, *b, c = items
>>> print(b)
['b', 'one', 10, 11]
>>> *_, a, b = items
>>> print(a)
11