regebro / tzlocal

A Python module that tries to figure out what your local timezone is

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Pinned] ValueError: Timezone offset does not match system offset

regebro opened this issue · comments

You will get this error, if there is something wrong in your computers time zone configuration. Ask for help with figuring out what is wrong here.

Common reasons:

  • Your country's time zone standard has recently changed, and the OS config has been updated, but you are running an old version of pytz.

  • You are running under some sort of "almost virtualized" OS, like Cygwin, and the timezone configuration in this Linux-like environment doesn't match the Windows configuration.

Hi @regebro I was facing similar issue and @jcampbell pointed me to this discussion. I'm using the latest version of pytz (2019.3) and have already tried to change the system timezone, but nothing helped. To give more context, this year in Brazil the light saving adjustment was cancelled by the government, but I believe the network time has not adjusted that. So if I use the network time my clock gets 1h ahead of the official brazilian time. I have turned off network time and set it 1h earlier, to adjust to the official brazilian time, but that did not worked also. I have tried to import tzlocal and run get_localzone() but then I get the problem. Below you can see the problem when I try to run great expectations:


ValueError Traceback (most recent call last)
in
2 import os
3 import great_expectations as ge
----> 4 import great_expectations.jupyter_ux
5 import pandas as pd

~/anaconda3/envs/laod/lib/python3.6/site-packages/great_expectations/jupyter_ux/init.py in
308 # When importing the jupyter_ux module, we set up a preferred logging configuration
309 logger = logging.getLogger("great_expectations")
--> 310 setup_notebook_logging(logger)

~/anaconda3/envs/load/lib/python3.6/site-packages/great_expectations/jupyter_ux/init.py in setup_notebook_logging(logger)
83 """
84
---> 85 def posix2local(timestamp, tz=tzlocal.get_localzone()):
86 """Seconds since the epoch -> local time as an aware datetime object."""
87 return datetime.fromtimestamp(timestamp, tz)

~/anaconda3/envs/load/lib/python3.6/site-packages/tzlocal/unix.py in get_localzone()
163 global _cache_tz
164 if _cache_tz is None:
--> 165 _cache_tz = _get_localzone()
166
167 return _cache_tz

~/anaconda3/envs/load/lib/python3.6/site-packages/tzlocal/unix.py in _get_localzone(_root)
88 # We are using a file in etc to name the timezone.
89 # Verify that the timezone specified there is actually used:
---> 90 utils.assert_tz_offset(tz)
91 return tz
92

~/anaconda3/envs/load/lib/python3.6/site-packages/tzlocal/utils.py in assert_tz_offset(tz)
36 tz_offset, system_offset
37 )
---> 38 raise ValueError(msg)

ValueError: Timezone offset does not match system offset: -10800 != -7200. Please, check your config files.

Hi @bruno-curta, I'm from Brazil too, I had the same error, I could fix it using the $tzselect (https://www.cyberciti.biz/faq/linux-unix-set-tz-environment-variable/) to select the timezone.

Hi @GislaineCurty thanks for the tip! I have followed this link and tzselect, but after selecting Americas/Brazil/Southeast the time remains 1h ahead. Have you forced it to a different timezone or changed it manually? Thanks!

@GislaineCurty never mind, I got it now. I have forced it to UTC3 and appended it to my .profile, now it is working great. Thanks for that!

Pytz should include the changed rules, so it does indeed sound like your local operating systems hasn't been updated to the last release of the iana tz database.

Hello all,
What would be the proper way to resolve this in Cygwin?
I'm in Greece (UTC+02:00).

$ tzset
Europe/Athens

$ echo $TZ
Europe/Athens

$ python -i
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from tzlocal import get_localzone
>>> get_localzone()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\gmargari\Documents\GitHub\home_scraper\env\lib\site-packages\tzlocal\win32.py", line 95, in get_localzone
    utils.assert_tz_offset(_cache_tz)
  File "C:\Users\gmargari\Documents\GitHub\home_scraper\env\lib\site-packages\tzlocal\utils.py", line 38, in assert_tz_offset
    raise ValueError(msg)
ValueError: Timezone offset does not match system offset: 7200 != 0. Please, check your config files.

So I suppose the "timezone offset" is correct, but the "system offset" is not. Is there anything I could do to fix this inconsistency?

Thanks.

Hi @gmargari I have followed the instructions in this link https://www.cyberciti.biz/faq/linux-unix-set-tz-environment-variable/, shared by @GislaineCurty and it fixed my problem, after I set my timezone to UTC 3. I'm not sure it was a system outdated version, but a problem with the fact this year specific we are not following the traditional daylight savings. Using tzselect and changing the system timezone helped in my case.

[BUG] "Timezone offset does not match system offset: {0} != {1}." if automatic daylight saving time is disabled from windows settings.
If automatic daylight saving time is disabled from windows settings, this error appears. The problem is that by enabling automatic daylight saving time, windows adds 1 more WRONG hour. I can't keep a wrong clock on windows server. Europe / Rome (time: 14:12; with the option enabled: 15:12 BAD TIME).
To Reproduce
1 leave automatic daylight saving time disabled.
image
I write here instead of making an identical new issue. If I wrote wrong (instead of creating a new issue, I apologize in advance).

@zFerry98 No, it adds one more CORRECT hour. It is currently daylight savings in Rome. It should add one hour.

tzlocal in this case errors out because your computer is incorrectly configured, and that confuses it. You can get rid of the error by setting a TZ environment variable so it matches your incorrect setting, but it's honestly better to configure your computer correctly.

@zFerry98 No, it adds one more CORRECT hour. It is currently daylight savings in Rome. It should add one hour.

tzlocal in this case errors out because your computer is incorrectly configured, and that confuses it. You can get rid of the error by setting a TZ environment variable so it matches your incorrect setting, but it's honestly better to configure your computer correctly.

OK thanks. Windows Server seems to force the time from the internet, thus creating problems. I forced the administrative permissions to set the time back and then activated the Daylight. Now it seems to work. Thank you.

In my case, the computer's hardware clock was wrong. I fixed it as described here by running
sudo ntpd -qg

Just chucking in a couple of my time-zoned coins here...

I had this same error with great_expectations. I'm using a Windows 10 VM and there is little chance I can get administration privileges to set the TimeZone info.

assert_tz_offset is throwing the ValueError, because my timezone is retuning 'Etc/GMT' or GMT0. I'm currently in BST, which is essentially GMT+1. Hence the exception. And yes it's probably misconfigured.

Would it be better perhaps if instead of throwing an exception, it raised a Warning. Alternatively a way of setting configuration to use System Vs Local. I understand the point about misconfiguration, however what if I was intentionally misconfiguring a system. Just seems this could do with a little more 'configuration'.

I would be happy to make a PR if there was some concessions around this issue.

"I'm using a Windows 10 VM"

Strange that you get that on Windows, I have to say... Unless the local windows is set to not follow DST. I had another issue about that. I should look into handling that.

"Would it be better perhaps if instead of throwing an exception, it raised a Warning."

No, because then the software you are using to get your local timezone doesn't give you the local timezone.

You can always override it by setting a TZ environment variable. TZ="Europe/London" will make it not even look at the configuration. That's probably the way to go in your case.

I tried setting a windows env/var with ps (Set-Variable -Name "TZ" Value "Europe/London") as suggested and sadly it didn't make a difference. I also tried setting a global var and the same issue. It still throws the Timezone offset error.

Ah, right you are. TZ environment are really a Unix thing and I didn't support them under Windows, I forgot about that. Maybe I should fix that...

Even if you can't change the timezone configuration on the VM, can you view it? Could you screenshot this page?

image

I've managed to fix it for the moment by changing TimeZoneKeyName in the registry to "GMT Standard Time". The default value was UTC, which I think it was, why it resolved to Etc/GMT. I can't screenshot unfortunately (client VM...). It was "Set time auto" and UTC +00 (Dublin..London)

Perhaps there is a consideration here to include in the exception message, to add a bit more info around the zone-names, which have been retrieved alongside the offset: {} != {}.

Adding the TZ env/var option though would definitely be a handy addition :)

Really appreciate the help BTW and let me know if you want any PRs I maybe be able to help with.

Yes, "GMT Standard Time" is Windows way of saying "Europe/London", so that's correct.

There must be something weird going on here, that when you get the time zone offset it returns the hosts offset, while the VM is set to UTC. VM's are tricky.

Got this error running khal on Manjaro linux.

Turns out Manjaro creates a file /etc/timezone on install which is not updated when the tz is switched using timedatectl. This library seems to use this file somehow, leading to two different values. Updating or deleting that file resolved the error message for me.

Yeah, the 4.0 release, currently in 4.0b1, will be more explicit about these errors.

image

The runtime in generated data docs for validations are greater by an offset of +5:30 from the current IST time. The time set in run time is greater by +5:30 which is the offest of the IST(GMT+05:30) timezone.

What might be the cause of this ?

Try installing tzlocal 4.0b3, it is more explicit in what causes these errors.

4.0 is released, and most of these errors should be gone.

I get the same error on my mac, My systems timezone is set to Marrakesch/Marokko, as it should be, but the tzlocal says Timezone offset does not match system offset: 0 != 3600 (is it because of the special summer time here maybe?)

No, it handles summertime by itself. It's probably a misconfiguration. I'm not sure what the standard zoneinfo name is for Morocco, I think it might be Africa/Casablanca?

Could you download version 5.0b1, and run the following code in a Python console?

import logging
logging.basicConfig(level="DEBUG")
import tzlocal
tzlocal.get_localzone_name()
tzlocal.get_localzone()

I have the same problem with Africa/Casablanca on Ubuntu 22.04

Morocco has a history of messing with time zones on a very short term basis and without warning. Right now it's "Ramadan time" for one month...

❯ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.basicConfig(level="DEBUG")
>>> import tzlocal
>>> tzlocal.get_localzone_name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tzlocal' has no attribute 'get_localzone_name'. Did you mean: 'get_localzone'?
>>> tzlocal.get_localzone()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/tzlocal/unix.py", line 165, in get_localzone
    _cache_tz = _get_localzone()
  File "/usr/lib/python3/dist-packages/tzlocal/unix.py", line 90, in _get_localzone
    utils.assert_tz_offset(tz)
  File "/usr/lib/python3/dist-packages/tzlocal/utils.py", line 46, in assert_tz_offset
    raise ValueError(msg)
ValueError: Timezone offset does not match system offset: 0 != 3600. Please, check your config files.
❯ TZ=Africa/Casablanca python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.basicConfig(level="DEBUG")
>>> import tzlocal
>>> tzlocal.get_localzone_name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tzlocal' has no attribute 'get_localzone_name'. Did you mean: 'get_localzone'?
>>> tzlocal.get_localzone()
<DstTzInfo 'Africa/Casablanca' LMT-1 day, 23:30:00 STD>

PS: My system timezone should be just fine

❯ sudo dpkg-reconfigure tzdata

Current default time zone: 'Africa/Casablanca'
Local time is now:      Tue 11 Apr 09:20:35 +00 2023.
Universal Time is now:  Tue Apr 11 09:20:35 UTC 2023.

I never had to explicitly set the $TZ user variable before

@tbaumann Ahm, if they changed it recently, the database may not have been updated, and then you could get this error, I guess...

>>> import zoneinfo
>>> import datetime
>>> tz = zoneinfo.ZoneInfo("Africa/Casablanca")
>>> tz.utcoffset(datetime.datetime.now())
datetime.timedelta(0)
>>> tz.utcoffset(datetime.datetime(2023, 3, 1))
datetime.timedelta(seconds=3600)
>>> tz.utcoffset(datetime.datetime(2023, 4, 1))
datetime.timedelta(0)
>>> tz.utcoffset(datetime.datetime(2023, 5, 1))
datetime.timedelta(seconds=3600)

So, yes, my zoneinfo database includes Ramadan time. And so does yours, as far as I can tell, because your error says:

ValueError: Timezone offset does not match system offset: 0 != 3600.

In otherwords, your zoneinfo database says that your offset should be 0, because it's Ramadan, but your system says the offset is 3600. And that's curious; because your localtime says +00, so it says the offset IS zero.

I will have to do some more checks later today. For the time being, just setting TZ="Africa/Casablanca" will fix it, it doesn't make the offset check if you explicitly set the TZ variable.

@tbaumann Ahm, if they changed it recently, the database may not have been updated, and then you could get this error, I guess...

Unfortunately Morocco has a history of doing that. 😓
2019 they announced just weeks before the clocks changed that they will not switch back to summer time.
And then less than two years later they decided, with equally little ahead warning, to go back to this time change nonsense.
And every year they seem to be surprised when Ramadan happens instead of planning ahead.

Needless to say, computers hate this every time. 😄

Well, it's not really Morocco's fault. Morocco is on permanent DST. Except for during Ramadan. However, IANA doesn't treat Ramadan time as a return to non-DST, but treats it as just an arbitrary 1-hour shift, and instead says that Morocco is 1 hour before GMT both with and without DST. So when looking up the difference, tzlocal says "Ah, this is not DST" and returns the non-DST offset, which, because IANA said Morocco ALWAYS is one hour off, means a 3600 seconds offset. Even though the actual offset is 0.

I released 5.0b2 to deal with that.

@tbaumann @jacksbox Please test.

Well, it's not really Morocco's fault. Morocco is on permanent DST. Except for during Ramadan. However, IANA doesn't treat Ramadan time as a return to non-DST, but treats it as just an arbitrary 1-hour shift, and instead says that Morocco is 1 hour before GMT both with and without DST. So when looking up the difference, tzlocal says "Ah, this is not DST" and returns the non-DST offset, which, because IANA said Morocco ALWAYS is one hour off, means a 3600 seconds offset. Even though the actual offset is 0.

I released 5.0b2 to deal with that.

@tbaumann @jacksbox Please test.

WORKSFORME

❯ cd git/regebro/tzlocal/
tilli in tzlocal on  master is 📦 v5.0b2.dev0 via 🐍 v3.10.6 (test)
❯ ls
CHANGES.txt  MANIFEST.in  README.rst      setup.cfg  tests/    update_windows_mappings.py*
LICENSE.txt  Makefile     pyproject.toml  setup.py   tzlocal/
tilli in tzlocal on  master is 📦 v5.0b2.dev0 via 🐍 v3.10.6 (test)
❯ less ^C
tilli in tzlocal on  master is 📦 v5.0b2.dev0 via 🐍 v3.10.6 (test)
❯ python3 -m pip install .
Processing /home/tilli/git/regebro/tzlocal
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: tzlocal
  Building wheel for tzlocal (pyproject.toml) ... done
  Created wheel for tzlocal: filename=tzlocal-5.0b2.dev0-py3-none-any.whl size=20764 sha256=f6fee770adee0affe4754c64d0d1b9fcb63f109ef6316a6f039fda1ea85c6b1b
  Stored in directory: /tmp/pip-ephem-wheel-cache-ui2v5sdw/wheels/d4/3e/99/105ce4250d0ea2a38c08e6e93ce1c6ea3c2c16a4875f05f1af
Successfully built tzlocal
Installing collected packages: tzlocal
Successfully installed tzlocal-5.0b2.dev0

[notice] A new release of pip available: 22.2.2 -> 23.0.1
[notice] To update, run: pip install --upgrade pip
tilli in tzlocal on  master [?] is 📦 v5.0b2.dev0 via 🐍 v3.10.6 (test)
❯ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.basicConfig(level="DEBUG")
>>> import tzlocal
>>> tzlocal.get_localzone_name()
DEBUG:root:/etc/timezone found, contents:
 Africa/Casablanca

DEBUG:root:/etc/localtime found
DEBUG:root:2 found:
 {'/etc/timezone': 'Africa/Casablanca', '/etc/localtime is a symlink to': 'Africa/Casablanca'}
'Africa/Casablanca'
>>> tzlocal.get_localzone()
DEBUG:root:/etc/timezone found, contents:
 Africa/Casablanca

DEBUG:root:/etc/localtime found
DEBUG:root:2 found:
 {'/etc/timezone': 'Africa/Casablanca', '/etc/localtime is a symlink to': 'Africa/Casablanca'}
zoneinfo.ZoneInfo(key='Africa/Casablanca')
>>>
>>>
tilli in tzlocal on  master [?] is 📦 v5.0b2.dev0 via 🐍 v3.10.6 (test)
❯ echo $TZ

Apologies for my rather verbose shell prompt.

Great!

Well, it's not really Morocco's fault. Morocco is on permanent DST. Except for during Ramadan. However, IANA doesn't treat Ramadan time as a return to non-DST, but treats it as just an arbitrary 1-hour shift, and instead says that Morocco is 1 hour before GMT both with and without DST.
Thanks for explaining that. I live there and I never quite understood it

@regebro I export now the tz Africa/Casablanca on my dev machine (I can't add it to the code, my servers are not in Marocco ;)) and that does the trick. I hope it will not mess with other parts of my system though...

@jacksbox If you are in Marocco it should make no difference. Upgrading to 5.0b2 will also likey fix the issue, or at worst, change it from an error to a warning.