6

I am new to Python. I am reading about dates and times from the lovely book 'Python 3 Standard Library by Example' by Doug Hellmann and I stumbled upon this code snippet:

import time
import os


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


if __name__ == '__main__':
    print('Default: ')
    show_zone_info()

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

    for zone in ZONES:
        os.environ['TZ'] = zone
        # time.tzset()      # Only available on Unix
        print(zone, ':')
        show_zone_info()

Problem is, time.tzset() is only available on Unix and without it on Windows machine, timezone doesn't change during the run time of the code. What is the alternative to time.tzset() on Windows? (I am running Python 3.8.3 on Windows 10 at the time of asking this question.)

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 1
    Have you looked at this link... https://stackoverflow.com/questions/4360981/make-python-respond-to-windows-timezone-changes – avrsanjay May 25 '20 at 14:24
  • @avrsanjay, it doesn't work. At least I couldn't make it work. The solution responds to Windows timezone changes. I, on the other hand, am changing `os.environ['TZ']`. Besides, it looks like the solution is for Python2 written 9 years ago. I was wondering if there are any other possible solutions since then. – SagittariusAStar_MW May 26 '20 at 06:52
  • @MrFuppes, I have no problem with getting the timezone, I have a problem in setting the timezone. – SagittariusAStar_MW May 26 '20 at 06:58
  • @SagittariusAStar_MW, sorry, I totally misread this, apologies! Having a look at [the docs](https://docs.python.org/3/library/time.html#time.tzset), I see why the method could be useful but the docs also say that the function should not be relied on. I would definitely suggest to work with specified timezones instead of altering the behaviour of e.g. `localtime()` - I imagine this can create a total mess... – FObersteiner May 26 '20 at 07:07
  • @MrFuppes, um, the note says that behavior changed by setting `os.environ['TZ']` should not be relied upon *without* calling `tzset()`. It doesn't exactly say `tzset()` is unreliable. Testing out code under different timezone may be necessary for debugging. – SagittariusAStar_MW May 26 '20 at 07:33
  • @SagittariusAStar_MW: I mean, if you work with `datetime` objects (which rely on functions from the `time` module), it is just easier and more readable to explicitly specify the `tzinfo` property from my experience. But that may depend on the situation / the project you work on. – FObersteiner May 26 '20 at 07:41
  • @MrFuppes, I understand. I will keep the question standing to see if anybody has any solution to this specific problem. Thanks. – SagittariusAStar_MW May 26 '20 at 07:54

0 Answers0