stub42 / pytz Goto Github PK
View Code? Open in Web Editor NEWpytz Python historical timezone library and database
License: MIT License
pytz Python historical timezone library and database
License: MIT License
Hi!
I found a time zone issue which changed Pyongyang(North Korea) time zoned recently.
According to 'https://en.wikipedia.org/wiki/Time_in_North_Korea', I found 'On 29 April 2018, North Korean leader Kim Jong-un announced his country would be returning to UTC+9 to realign its clocks with South Korea. '. It based on the Guadian Newspaper('https://www.theguardian.com/world/2018/may/05/time-for-change-north-korea-moves-clocks-forward-to-match-south')
Below code is not match the Wiki.
import pytz
import datetime
def main():
seoul = pytz.timezone('Asia/Seoul')
print(seoul.localize(datetime.datetime.now()))
pyongyang = pytz.timezone('Asia/Pyongyang')
print(pyongyang.localize(datetime.datetime.now()))
if __name__ == '__main__':
main()
The result is below.
2018-06-19 18:23:36.818206+09:00
2018-06-19 18:23:36.818469+08:30
Second result should be equal to '2018-06-19 18:23:36.818469+09:00'
Could you change code and and document(https://github.com/stub42/pytz/blob/master/tz/asia#L1997)?
And When I test the previous example, I found another interesting sample code.
>>> import pytz
>>> from datetime import datetime
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> seoul = pytz.timezone('Asia/Seoul')
>>> seoul
<DstTzInfo 'Asia/Seoul' KST+8:30:00 STD>
>>> pyongyang = pytz.timezone('Asia/Pyongyang')
>>> pyounyang
<DstTzInfo 'Asia/Pyongyang' KST+8:30:00 STD>
Finally, I found another interesting document. You described world timezone. Previsous menthioned, I think it should be changed.
https://github.com/stub42/pytz/blob/master/tz/asia#L47
https://github.com/stub42/pytz/blob/master/tz/asia#L50
-> I think it should be removed at '8:30 KST KDT Korea when at +0830', maintained at ''9:00 KST KDT Korea when at +09'.
Thanks in advance.
Would be great to have a single "base" class for all errors that could be raised by the library.
Looking at https://github.com/stub42/pytz/blob/master/src/pytz/exceptions.py, there are two base classes at the moment: UnknownTimeZoneError
and InvalidTimeError
.
Without a guaranteed single base class, a package upgrade may add new error types, without call-sites being updated about the change.
There is an inconsistency when converting a datetime that is in UTC to pytz.timezone('America/Sao_Paulo'), instead of discounting 3 hours, it is only discounting 2 hours, the library is considering that Brazil is in daylight saving time, that no longer exists.
To get the correct conversion, you need to use pytz.timezone('Etc/GMT+3')
Fix the 'America/Sao_Paulo' to discount the hours in the correct way
As a checked before 1914 the timezone in Sao Paulo was -3:06 but it changed on that year.
The current version of pytz is returning the timezone as it's -3:06 from UTC instead of -3:00
You can check buy using this:
from datetime import datetime
import pytz
now = datetime(2021, 2, 3, 15, 0, 0, 0, pytz.timezone("America/Sao_Paulo"))
as_utc = now.astimezone(pytz.UTC)
I'm trying to package your module as an rpm package. So I'm using the typical PEP517 based build, install and test cycle used on building packages from non-root account.
python3 -sBm build -w
Here is pytest output:
+ PYTHONPATH=/home/tkloczko/rpmbuild/BUILDROOT/python-pytz-2021.3-2.fc35.x86_64/usr/lib64/python3.8/site-packages:/home/tkloczko/rpmbuild/BUILDROOT/python-pytz-2021.3-2.fc35.x86_64/usr/lib/python3.8/site-packages
+ /usr/bin/pytest -ra
=========================================================================== test session starts ============================================================================
platform linux -- Python 3.8.12, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /home/tkloczko/rpmbuild/BUILD/pytz-release_2021.3/src
collected 41 items / 1 error / 40 selected
================================================================================== ERRORS ==================================================================================
________________________________________________________________ ERROR collecting pytz/tests/test_tzinfo.py ________________________________________________________________
pytz/tests/test_tzinfo.py:40: in <module>
GMT = pytz.timezone('GMT')
../../../BUILDROOT/python-pytz-2021.3-2.fc35.x86_64/usr/lib/python3.8/site-packages/pytz/__init__.py:179: in timezone
zone = _case_insensitive_zone_lookup(_unmunge_zone(zone))
../../../BUILDROOT/python-pytz-2021.3-2.fc35.x86_64/usr/lib/python3.8/site-packages/pytz/__init__.py:205: in _case_insensitive_zone_lookup
_all_timezones_lower_to_standard = dict((tz.lower(), tz) for tz in all_timezones) # noqa
E NameError: name 'all_timezones' is not defined
========================================================================= short test summary info ==========================================================================
ERROR pytz/tests/test_tzinfo.py - NameError: name 'all_timezones' is not defined
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================= 1 error in 1.64s =============================================================================
Looks like smth wrong with datetime difference with pytz timezones. I have such code on Python 3.6:
import datetime
import pytz
dep_datetime = pytz.timezone('America/New_York').localize(
datetime.datetime.strptime(
'2019-11-03 01:05:00',
'%Y-%m-%d %H:%M:%S'
)
)
arrival_datetime = pytz.timezone('Europe/Amsterdam').localize(
datetime.datetime.strptime(
'2019-11-03 13:00:00',
'%Y-%m-%d %H:%M:%S'
)
)
diff = arrival_datetime - dep_datetime
print(diff)
diff_minutes = int((diff).total_seconds() / 60)
print(diff_minutes)
exit(1)
Returns:
5:55:00
355
I have similar code on PHP and go, and their result is 415 minutes (6 hours 55 minutes). Such result also shows online calculator: https://www.timeanddate.com/date/timezoneduration.html?d1=3&m1=11&y1=2019&d2=3&m2=11&y2=2019&h1=01&i1=05&s1=00&h2=13&i2=00&s2=&
I also checked this case in docker (latest python, latest php and go) and results didn't change - 355 minutes in python, 415 in other languages.
Could you help me with this case?
This is copy of https://bugs.launchpad.net/pytz/+bug/1829385
After daylight savings started earlier this week we are now seeing:
pytz.exceptions.UnknownTimeZoneError: 'BST'
pytz show time zone for Iran +3:26 which it is not right.
from pytz import timezone
print(timezone('Iran'))
<DstTzInfo 'Iran' LMT+3:26:00 STD>
right time zone is +3:30 !
I'm trying to have a script that works with local time in Ireland but it seems that when you set a datetime object to Europe/Dublin and convert to UTC it adds 25 minutes and doesn't offset during DST.
>>> import datetime, pytz
>>> test = datetime.datetime(2018, 3, 1, 8, tzinfo=pytz.timezone('Europe/Dublin'))
>>> test.astimezone(pytz.timezone('UTC')).time()
datetime.time(8, 25)
>>> testDST = datetime.datetime(2018, 3, 30, 8, tzinfo=pytz.timezone('Europe/Dublin'))
>>> testDST.astimezone(pytz.timezone('UTC')).time()
datetime.time(8, 25)
It appears that it might be using Dublin Mean Time, which has been defunct since 1916.
Interestingly, this does not happen when going from UTC to Europe/Dublin.
>>> import datetime, pytz
>>> test = datetime.datetime(2018, 3, 1, 8, tzinfo=pytz.timezone('UTC'))
>>> test.astimezone(pytz.timezone('Europe/Dublin')).time()
datetime.time(8, 0)
>>> testDST = datetime.datetime(2018, 3, 30, 8, tzinfo=pytz.timezone('UTC'))
>>> testDST.astimezone(pytz.timezone('Europe/Dublin')).time()
datetime.time(9, 0)
#!/usr/bin/python3.5
from dateutil.parser import parse
import pytz
lists = [
"20170824010000 +0300",
"20170824015500 +0300",
"20170824034500 +0300",
"20170824052500 +0300",
"20170824210000 +0300",
"20170824232500 +0300"
]
for row in lists:
print (parse(row).replace(tzinfo=pytz.timezone('Europe/Moscow')))
result:
2017-08-24 01:00:00+02:30
2017-08-24 01:55:00+02:30
2017-08-24 03:45:00+02:30
2017-08-24 05:25:00+02:30
2017-08-24 21:00:00+02:30
2017-08-24 23:25:00+02:30
I think the way pytz info get printed by the interpreter is a bit unpractical. For example:
datetime.datetime(2020, 9, 9, 8, 0, tzinfo=<UTC>)
The reason for the inpracticality is that this cannot be put right into python back:
>>>datetime.datetime(2020, 9, 9, 8, 0, tzinfo=<UTC>)
File "<ipython-input-77-304f010bd0d1>", line 1
datetime.datetime(2020, 9, 9, 8, 0, tzinfo=<UTC>)
^
SyntaxError: invalid syntax
Would there be a way to make the output printed directly usable again in the interpreter? Printing datetime.datetime(2020, 9, 9, 8, 0, tzinfo=pytz.utc) for example, or something like that?
Note that this is a migration from https://bugs.python.org/issue41750 .
$ python src/setup.py bdist_wheel
Traceback (most recent call last):
File "src/setup.py", line 25, in <module>
assert len(resources) > 10, 'zoneinfo files not found!'
AssertionError: zoneinfo files not found!
This only started happening ever since the most recent commits.
I tried running python setup.py install
and I get the same AssertionError
Reproducible example:
>>> import datetime as dt
>>> import pytz
>>> today = dt.datetime.utcfromtimestamp(1573516800)
datetime.datetime(2019, 11, 12, 0, 0)
>>> today.replace(tzinfo=pytz.timezone('Europe/Madrid')).timestamp()
1573517700.0
>>> today.replace(tzinfo=pytz.timezone('Etc/GMT+1')).timestamp()
1573520400.0
Version:
>>> pytz.__version__
'2019.3'
The 2020d release came out a week ago, 2020-10-21 ( https://www.iana.org/time-zones ), and includes some last minute DST changes to Fiji and Palestine that took effect over the weekend. Can you update to include it?
Also reported on launchpad but then found this repo: https://bugs.launchpad.net/pytz/+bug/1901882
Hi, All. I am trying to find the timezone information for Sacramento, California but pytz.all_timezones does not have it? Can someone points out how can I find the timezone information for California?
Thanks.
to reproduce this bug run this lines of python code
from datetime import datetime
from pytz import FixedOffset, timezone
tz1 = FixedOffset(420)
dt = tz1.localize(datetime.now())
tz2 = timezone('America/Denver')
tz2.normalize(dt)
this raise this exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/ali/work/freelancing/vincent/chills_students/env/lib/python3.6/site-packages/pytz/tzinfo.py", line 252, in normalize
offset = dt.tzinfo._utcoffset
AttributeError: '_FixedOffset' object has no attribute '_utcoffset'
I checked the code and seems in "_FixedOffset" class we should rename "self._offset" to "self._utcoffset"
I am confused by the following behavior:
>>> import pytz
>>> pytz.__version__
'2018.3'
>>> utc = pytz.timezone('UTC')
>>> la = pytz.timezone('America/Los_Angeles')
>>> isinstance(utc, pytz.tzinfo.BaseTzInfo)
False
>>> isinstance(la, pytz.tzinfo.BaseTzInfo)
True
Is this intended, and if so, why?
Thanks!
Hi,
I'm having an AttributeError: module 'posixpath' has no attribute 'sep'
because this if
statement. I'm using python 3.10.4.
I'm not using pytz
directly, but instead, I'm profiling a web app and that happens when I start the profiler (scalene) with scalene app.py
and PyBabel calls pytz
. If needed I can paste here the traceback.
However, after taking a look at the os
module, indeed there isn't an os.path.sep
attribute. But there is os.sep
or os.pathsep
. In this case, I think the most appropriate method would be the os.sep
because it returns the OS path separator. If this is a real issue with pytz
, I'm happy to provide PR to fix it.
Cheers
the current version Time Zone Database is 2021e, so 2021c seems outdated. This might cause invalid UTC offsets like e.g.
from datetime import datetime
import pytz
>>> dt = datetime.fromisoformat('2046-05-31 22:00:00+00:00').astimezone(pytz.timezone("Europe/Paris"))
>>> print(dt)
2046-05-31 23:00:00+01:00
# should be
# 2046-06-01 00:00:00+02:00
>>> print(pytz.__version__)
2021.3
from zoneinfo import ZoneInfo
>>> dt = datetime.fromisoformat('2046-05-31 22:00:00+00:00').astimezone(ZoneInfo("Europe/Paris"))
>>> print(dt)
2046-06-01 00:00:00+02:00
>>> import tzdata
>>> print(tzdata.IANA_VERSION)
2021e
Python 3.9.4 on Windows 10
pandas-dev/pandas#12823
Please check the error in the link above
df2_5['Time'].dt.tz_localize('ETC/GMT+2')
cause the localization to be
2489 2020-03-30 08:00:00-02:00
2490 2020-03-30 09:00:00-02:00
2491 2020-03-30 10:00:00-02:00
2492 2020-03-30 11:00:00-02:00
2493 2020-03-30 12:00:00-02:00
instead of +2
Unless I'm using it wrong
Would there be any interest in a PR to add typing for mypy compliance? The main benefits are better IDE integration and improved static type checking on projects that use pytz
Effort is pretty minimal, mypy only raises 14-18 errors currently, depending on the python version.
A stubs repo already does exist: much of that could likely https://github.com/python/typeshed/tree/master/stubs/pytz/pytz
Type hinting is quite easy in python 3.6+. Not sure how long compatibility for python 2.7/3.5 (seen in pipelines) is intended for but that's doable too, just less elegant https://mypy.readthedocs.io/en/stable/cheat_sheet.html
Downloading pytz-2009r.zip (522 kB)
ERROR: Command errored out with exit status 1:
command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ra09a851/pytz_1a6a05111ba743cb89f02f94152bbb49/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ra09a851/pytz_1a6a05111ba743cb89f02f94152bbb49/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-kil48ik2
cwd: /tmp/pip-install-ra09a851/pytz_1a6a05111ba743cb89f02f94152bbb49/
Complete output (6 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-install-ra09a851/pytz_1a6a05111ba743cb89f02f94152bbb49/setup.py", line 11
print 'Python 2.3 install requires setuptools'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('Python 2.3 install requires setuptools')?
pip 20.3
python 3.7
As per Wikipedia, the IANA time zone database has the following zones for Argentina:
America/Argentina/Buenos_Aires – Buenos Aires (BA, CF)
America/Argentina/Cordoba – most locations (CD, CC, CR, ER, FO, MN, SF)
America/Argentina/Salta (SA, LP, NQ, RN)
America/Argentina/Jujuy – Jujuy (JY)
America/Argentina/Tucuman – Tucuman (TM)
America/Argentina/Catamarca – Catamarca (CT), Chubut (CH)
America/Argentina/La Rioja – La Rioja (LR)
America/Argentina/San Juan – San Juan (SJ)
America/Argentina/Mendoza – Mendoza (MZ)
America/Argentina/San Luis – San Luis (SL)
America/Argentina/Rio Gallegos – Santa Cruz (SC)
America/Argentina/Ushuaia – Tierra del Fuego (TF)
America/Argentina/Santiago_del_Estero (SE)
I didn't check them all, but some of them are definitely missing. For example "America/Argentina/Santiago_del_Estero".
Running this script with pytz==2020.1
and backports.zoneinfo==0.2.0
, I find 34 examples of zones where pytz
reports DST of > 1 hour, while backports.zoneinfo
reports DST of 1 hour:
import pytz
from backports import zoneinfo
from datetime import *
discrepancy_keys = {}
for key in pytz.all_timezones:
pz = pytz.timezone(key)
zz = zoneinfo.ZoneInfo(key)
for year in range(1900, 2040):
pd_winter = pz.localize(datetime(year, 1, 1)).dst()
zd_winter = datetime(year, 1, 1, tzinfo=zz).dst()
pd_summer = pz.localize(datetime(year, 7, 1)).dst()
zd_summer = datetime(year, 7, 1, tzinfo=zz).dst()
if pd_winter == zd_winter and pd_summer == zd_summer:
continue
if abs(pd_winter) > timedelta(hours=1) or abs(pd_summer) > timedelta(hours=1):
discrepancy_keys.setdefault(key, []).append(year)
Here's the list:
{'America/Argentina/Catamarca': [1992],
'America/Argentina/ComodRivadavia': [1992],
'America/Argentina/Cordoba': [1992],
'America/Argentina/Jujuy': [1992],
'America/Argentina/Mendoza': [1993],
'America/Argentina/Salta': [1992],
'America/Argentina/Tucuman': [1992],
'America/Catamarca': [1992],
'America/Cordoba': [1992],
'America/Indiana/Winamac': [2007],
'America/Jujuy': [1992],
'America/Mendoza': [1993],
'America/Rosario': [1992],
'Atlantic/Azores': [1942, 1943, 1944, 1945],
'Atlantic/Madeira': [1942, 1943, 1944, 1945],
'Europe/Belfast': [1941, 1942, 1943, 1944, 1945, 1947],
'Europe/Berlin': [1945],
'Europe/Brussels': [1940, 1941, 1942],
'Europe/Gibraltar': [1941, 1942, 1943, 1944, 1945, 1947],
'Europe/Guernsey': [1941, 1942, 1943, 1944, 1945, 1947],
'Europe/Isle_of_Man': [1941, 1942, 1943, 1944, 1945, 1947],
'Europe/Jersey': [1941, 1942, 1943, 1944, 1945, 1947],
'Europe/Lisbon': [1942, 1943, 1944, 1945],
'Europe/London': [1941, 1942, 1943, 1944, 1945, 1947],
'Europe/Luxembourg': [1940, 1941, 1942],
'Europe/Madrid': [1938],
'Europe/Monaco': [1941, 1942, 1943, 1944, 1945],
'Europe/Moscow': [1921],
'Europe/Paris': [1940, 1941, 1942],
'Europe/Simferopol': [1994],
'GB': [1941, 1942, 1943, 1944, 1945, 1947],
'GB-Eire': [1941, 1942, 1943, 1944, 1945, 1947],
'Portugal': [1942, 1943, 1944, 1945],
'W-SU': [1921]}
Looking at one example, America/Cordoba
in 1991-1992, it looks like they changed their base offset during the 1991 transition¹, so they jumped ahead 2 hours, then jumped back only 1 hour in the next transition, at which point they had 1 more transition to +3 and then stopped doing DST:
America/Cordoba Sun Mar 3 01:59:59 1991 UT = Sat Mar 2 23:59:59 1991 -02 isdst=1 gmtoff=-7200
America/Cordoba Sun Mar 3 02:00:00 1991 UT = Sat Mar 2 22:00:00 1991 -04 isdst=0 gmtoff=-14400
America/Cordoba Sun Oct 20 03:59:59 1991 UT = Sat Oct 19 23:59:59 1991 -04 isdst=0 gmtoff=-14400
America/Cordoba Sun Oct 20 04:00:00 1991 UT = Sun Oct 20 02:00:00 1991 -02 isdst=1 gmtoff=-7200
America/Cordoba Sun Mar 1 01:59:59 1992 UT = Sat Feb 29 23:59:59 1992 -02 isdst=1 gmtoff=-7200
America/Cordoba Sun Mar 1 02:00:00 1992 UT = Sat Feb 29 23:00:00 1992 -03 isdst=0 gmtoff=-10800
America/Cordoba Sun Oct 18 02:59:59 1992 UT = Sat Oct 17 23:59:59 1992 -03 isdst=0 gmtoff=-10800
America/Cordoba Sun Oct 18 03:00:00 1992 UT = Sun Oct 18 01:00:00 1992 -02 isdst=1 gmtoff=-7200
America/Cordoba Sun Mar 7 01:59:59 1993 UT = Sat Mar 6 23:59:59 1993 -02 isdst=1 gmtoff=-7200
America/Cordoba Sun Mar 7 02:00:00 1993 UT = Sat Mar 6 23:00:00 1993 -03 isdst=0 gmtoff=-10800
Looking at the way this is done in zoneinfo
, it seems like it might be just lucky that the algorithm assigns the DST offset based on the DST→STD transition and not on the STD → DST transition.
It may be better to check both the DST → STD and STD → DST transitions and see if there's disagreement, and if one of them assigns 1 hour, choose that one. America/Indiana/Winamac
had a similar transition in 2007 as well. What I find interesting with America/Indiana/Winamac
is that pytz
gets dst()
wrong in 2007, but not in 2008, when it uses EST
again. Not sure what that's about.
Looks like Europe/Simferopol
is a similar situation, except it goes EET (+2, STD) → EEST (+3, DST) → MSD (+4, DST) → MSK (+3, STD), with those last two repeating afterwards.
Europe/Madrid
is a bug in zoneinfo, they have STD → DST → Double DST → DST → STD, and zoneinfo
doesn't pick up on that.
¹Awesomely, it seems that America/Cordoba
also underwent their transition at the amazing edge case of February 29th at midnight.
Wrong timezone offset when printing isoformat of localized datetime for all timezones starts with "Etc/GMT" (Etc/GMT-1, Etc/GMT+1, ...)
Timezone offset of +07:00 of Etc/GMT+7 is printed as -07:00 (supposed to be printed as +07:00)
>>> import pytz
>>> from datetime import datetime
>>> now = datetime.now()
>>> now
datetime.datetime(2021, 12, 3, 16, 47, 48, 208044)
>>> dt_local = pytz.timezone("Asia/Ho_Chi_Minh").localize(now)
>>> dt_local.isoformat()
'2021-12-03T16:47:48.208044+07:00'
>>> dt_local = pytz.timezone("Etc/GMT+7").localize(now)
>>> dt_local.isoformat()
'2021-12-03T16:47:48.208044-07:00'
>>> dt_local = pytz.timezone("Etc/GMT-1").localize(now)
>>> dt_local.isoformat()
'2021-12-03T16:47:48.208044+01:00'
pytz==2021.3
get error:**pytz.exceptions.UnknownTimeZoneError: 'Can not find timezone '**
under windows10 system.
there is **TimeZoneKeyName**
key in "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation",but the value if empty.
winver : windows 10 20H2(19042.746)
In pytz.all_timezones, GMT-10 prints with the timezones in UTC+10. Likewise, GMT-11 prints with the timezones in UTC+11. This seems to be a consistent error.
from datetime import datetime, timedelta
import pytz
# print out all the timezones that are close (within 1h) to midday
now_dt = datetime.utcnow() #prints current date AND time in utc but it is naive to timezone because python is dumb.
midday = now_dt.replace(hour=12, minute=0, second=0, microsecond=0) #hour must = 12 in order to print where it is currently noon. hour cannot be omitted or else it will only run in utc. if hour = 6, then it will print wherever it is currently 6am for the hour.
#dt means datetime
for tz_name in pytz.all_timezones: #tz_name is anything. it's just being looped through all possible timezones to compare the current time to every possible timezone where it is noon.
local_tz = pytz.timezone(tz_name) #local_tz is our favorite timezone. this looks up the zone of our favorite timezone.
local_dt = now_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) # current date AND time in UTC is now in UTC for sure for sure. this is a timezone. we then declare this timezone to be the timezone for our favorite timezone, named local_tz.
now_in_local_tz = local_tz.normalize(local_dt) #accounts for daylight savings time. our favorite timezone gets renamed to now_in_local_tz.
diff = now_in_local_tz.replace(tzinfo=None) - midday #determines the difference between our favorite timezone, now accounted for daylight savings time, and wherever it is currently noon in the world.
if diff > timedelta(seconds=0) and diff < timedelta(seconds=3600): # 3600 seconds = 1 hour. timedelta() is for calculating the differences between times. this means that the time printed will be between 1 and 59 minutes. i think.
print(tz_name, diff)
>>>
Antarctica/DumontDUrville 0:46:16.887295
Antarctica/Macquarie 0:46:16.887295
Asia/Ust-Nera 0:46:16.887295
Asia/Vladivostok 0:46:16.887295
Australia/ACT 0:46:16.887295
Australia/Adelaide 0:16:16.887295
Australia/Brisbane 0:46:16.887295
Australia/Broken_Hill 0:16:16.887295
Australia/Canberra 0:46:16.887295
Australia/Currie 0:46:16.887295
Australia/Darwin 0:16:16.887295
Australia/Hobart 0:46:16.887295
Australia/Lindeman 0:46:16.887295
Australia/Melbourne 0:46:16.887295
Australia/NSW 0:46:16.887295
Australia/North 0:16:16.887295
Australia/Queensland 0:46:16.887295
Australia/South 0:16:16.887295
Australia/Sydney 0:46:16.887295
Australia/Tasmania 0:46:16.887295
Australia/Victoria 0:46:16.887295
Australia/Yancowinna 0:16:16.887295
Etc/GMT-10 0:46:16.887295
Pacific/Chuuk 0:46:16.887295
Pacific/Guam 0:46:16.887295
Pacific/Port_Moresby 0:46:16.887295
Pacific/Saipan 0:46:16.887295
Pacific/Truk 0:46:16.887295
Pacific/Yap 0:46:16.887295
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/buildenv2/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in call
return self.application(environ, start_response)
File "/buildenv2/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 157, in call
response = self.get_response(request)
File "/buildenv2/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 124, in get_response
response = self._middleware_chain(request)
File "/buildenv2/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 43, in inner
response = response_for_exception(request, exc)
File "/buildenv2/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 93, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/buildenv2/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 139, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/buildenv2/local/lib/python2.7/site-packages/django/views/debug.py", line 84, in technical_500_response
html = reporter.get_traceback_html()
File "/buildenv2/local/lib/python2.7/site-packages/django/views/debug.py", line 328, in get_traceback_html
return t.render(c)
File "/buildenv2/local/lib/python2.7/site-packages/django/template/base.py", line 207, in render
return self._render(context)
File "/buildenv2/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render
return self.nodelist.render(context)
File "/buildenv2/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render
bit = node.render_annotated(context)
File "/buildenv2/local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated
return self.render(context)
File "/buildenv2/local/lib/python2.7/site-packages/django/template/base.py", line 1040, in render
output = self.filter_expression.resolve(context)
File "/buildenv2/local/lib/python2.7/site-packages/django/template/base.py", line 732, in resolve
obj = template_localtime(obj, context.use_tz)
File "/buildenv2/local/lib/python2.7/site-packages/django/utils/timezone.py", line 195, in template_localtime
return localtime(value) if should_convert else value
File "/buildenv2/local/lib/python2.7/site-packages/django/utils/timezone.py", line 213, in localtime
timezone = get_current_timezone()
File "/buildenv2/local/lib/python2.7/site-packages/django/utils/timezone.py", line 97, in get_current_timezone
return getattr(_active, "value", get_default_timezone())
File "/buildenv2/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 124, in wrapper
result = user_function(*args, **kwds)
File "/buildenv2/local/lib/python2.7/site-packages/django/utils/timezone.py", line 79, in get_default_timezone
return pytz.timezone(settings.TIME_ZONE)
File "/buildenv2/local/lib/python2.7/site-packages/pytz/init.py", line 160, in timezone
if zone.upper() == 'UTC':
AttributeError: 'NoneType' object has no attribute 'upper'
2018-12-07 12:58:11,921 ERROR django.server "GET / HTTP/1.1" 500 59
👋 Hi! New contributor here. I'm updating the typing stubs for pytz in typeshed (PR#3393), specifically adding FixedOffset
's typing. I'm unsure about the kwarg though, _tzinfos
.
Here's the line I've put in typeshed. @stub42 Can you confirm the typing of _tzinfos
(and, of course, let me know if the other types are wrong). The typeshed tests run, and it looks right to me... but I don't know pytz well enough. Thanks!
I recently bumped version of pytz and was surprised with different results for Antarctica/Macquarie. Following code gives different results on version 2018.7 (offset -> 11:00:00) and 2020.5 (offset -> 10:00:00):
from pytz import timezone
from pandas import Timestamp
t = Timestamp("2020-05-10 03:00:00")
zone = timezone("Antarctica/Macquarie")
print(zone.utcoffset(t))
Is there some issue with DST for this particular timezone?
I filled this as a bug on python because I thought it was the datetime comparison. Apparently, it is actually something with pytz (which I don't fully understand).
https://bugs.python.org/issue38812
import pytz
import datetime
tzaware_time1 = datetime.time(7,30,tzinfo=pytz.timezone("America/Denver"))
tzaware_time2 = datetime.time(7,30,tzinfo=pytz.utc)
tzunaware_time = datetime.time(7, 30)
# This fails with exception: TypeError: can't compare offset-naive and offset-aware times
# even though both ARE tz aware.
tzaware_time1 < tzaware_time2
# This does NOT raise an exception and should since one is aware and one isn't.
tzunaware_time < tzaware_time1
I don't know how urgently pytz tends to get updated when the Olson database is revved, but I happened to notice that 2017c came out on 2017-10-20.
Solved, I had an older version installed
The current time zone for Nuuk is set to America/Godthab
but this has been changed since the last IANA report to 'America/Nuuk.
See Link to IANA
Inputting 'America/Nuuk' returns the following exception
pytz.exceptions.UnknownTimeZoneError: 'America/Nuuk'
Thanks for that great library
I'm trying to execute this code from a 2 year-old project:
import pytz
from django.utils import timezone
pytz.timezone('Europe/Madrid').normalize(timezone.now())
and it suddenly gives me this:
Traceback (most recent call last):
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\views\generic\base.py", line 119, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\tvand\Documents\repos\Mitios\weekplan\views.py", line 115, in get
return render(
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\shortcuts.py", line 24, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\backends\django.py", line 62, in render
return self.template.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 175, in render
return self._render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\loader_tags.py", line 208, in render
return template.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 177, in render
return self._render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\defaulttags.py", line 315, in render
match = condition.eval(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\defaulttags.py", line 878, in eval
return self.value.resolve(context, ignore_failures=True)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 712, in resolve
obj = self.var.resolve(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 842, in resolve
value = self._resolve_lookup(context)
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\django\template\base.py", line 909, in _resolve_lookup
current = current()
File "C:\Users\tvand\Documents\repos\Mitios\weekplan\models.py", line 28, in es_atrasada
fecha_asignacion = self._fecha_huso(self.fecha_asignacion)
File "C:\Users\tvand\Documents\repos\Mitios\weekplan\models.py", line 44, in _fecha_huso
pytz.timezone('Europe/Madrid').normalize(timezone.now())
File "C:\Users\tvand\Documents\repos\Mitios\venv\lib\site-packages\pytz\tzinfo.py", line 252, in normalize
offset = dt.tzinfo._utcoffset
I'm using:
Django==4.0.3
pytz==2022.1
I checked that django.utils.timezone.tzinfo
does have a utcoffset
. Has there been a change on pytz
concerning this or is it Django
's fault? Any idea on how to solve it?
Hi,
I am using your library extensively and love it. However recently I noticed what I believe is a bug in the UTC offsets for various timezones. It seems related to a 'premptive' switch back from daylight savings.
For example, here I create a naive datetime (2018-02-01 6:00:00) and localize it to the London timezone. However when I print the tz-aware datetime object, it shows GMT0:00:00 and when I print the utcoffset()
it also shows a difference of 0:00:00.
>>> local_date
datetime.datetime(2015, 2, 1, 6, 0)
>>> res_timezone_one
<DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>
>>> aware_datetime = res_timezone_one.localize(local_date)
>>> aware_datetime
datetime.datetime(2015, 2, 1, 6, 0, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)
>>> aware_datetime.utcoffset()
datetime.timedelta(0)
This is wrong, as London is one hour ahead of GMT at the moment (until October 28th). I am also getting a similar problem with America/Denver
.
Thanks,
Nathanael
I'm a little confused by the current behavior noted below:
In [2]: import datetime, pytz
In [3]: local = pytz.timezone("America/Los_Angeles")
In [4]: print local
America/Los_Angeles
In [5]: time_now = datetime.datetime.now();
In [6]: print time_now
2018-04-17 15:48:40.706613
In [7]: local_time_now = time_now.replace(tzinfo = local)
In [8]: print local_time_now
2018-04-17 15:48:40.706613-07:53
In [9]: utc_time_now = local_time_now.astimezone(pytz.utc)
In [10]: print utc_time_now
2018-04-17 23:41:40.706613+00:00
Is there a reason why there is a 7hr, 53min offset rather than the 7hrs that I am expecting?
In [11]: print pytz.VERSION
2016.4
When I create UTC date after 2038 year and then change the timezone to eg. 'Europe/Warsaw' the DST is wrong.
For example, in june Warsaw is in GMT+2 time zone so when I set UTC time to 10:00 the time in Warsaw should be 12:00.
Code to reproduce bug:
Date before 2038, gives 12:00. everything OK:
>>> utc_dt = datetime(2037, 6, 1, 10, 0, 0, tzinfo=pytz.utc)
>>> utc_dt
datetime.datetime(2037, 6, 1, 10, 0, tzinfo=<UTC>)
>>> loc_dt = utc_dt.astimezone(timezone('Europe/Warsaw'))
>>> loc_dt
datetime.datetime(2037, 6, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/Warsaw' CEST+2:00:00 DST>)
Date after 2038, should be 12:00, but gives 11:00:
>>> utc_dt = datetime(2038, 6, 1, 10, 0, 0, tzinfo=pytz.utc)
>>> utc_dt
datetime.datetime(2038, 6, 1, 10, 0, tzinfo=<UTC>)
>>> loc_dt = utc_dt.astimezone(timezone('Europe/Warsaw'))
>>> loc_dt
datetime.datetime(2038, 6, 1, 11, 0, tzinfo=<DstTzInfo 'Europe/Warsaw' CET+1:00:00 STD>)
Hi,
first, thanks for managing this nice library!
I have problems with mypy
when using the FixedOffset
function:
some_file.py:4: error: Module 'pytz' has no attribute 'FixedOffset'
I found out that this is probably related to "FixedOffset" not being exported in __all__
and thus also not present in typeshed
database. So my question is - Is the function (quite a useful one!) hidden by purpose or can it be public as well?
Thanks a lot,
Jan
Related: https://answers.launchpad.net/pytz/+question/671489
We are observing an unexpected OverflowError
from time.mktime
. So far we're only able to reproduce within Github Actions.
I'm unsure if the issue is related to pytz
. However, I thought it would make sense to open an issue here first to rule it out.
A minimally reproducible example of the issue is below:
import datetime
import time
import pytz
x = pytz.timezone('US/Pacific')
y = datetime.datetime(2017,5,26,15,30,16)
z = x.localize(y)
print(time.mktime(z.timetuple()))
The code above appears to work on Python 3.9 using pytz 2021.3 on OSX 11.6.1, Centos 7.9, Ubuntu 18.04 and macos-latest in Github Actions. However, it does not appear to work within ubuntu-latest on Github Actions. In all cases, Python and pytz are being sourced by conda.
An example log of the failure can be found here. The build configuration has been minimized as to only install Python 3.9 and pytz (latest).
A passing execution, on macos-latest, can be found here.
Please let me know if additional information would be helpful. I apologize if this issue is being opened on the wrong project, and if it instead would be better for python-dev. It does appear the issue has been noted with python-dev but closed on the assumption it was related to pytz
.
Thank you for your time, and all your hard work on this foundational project.
Hi there,
I'm trying to get the local timezone:
from tzlocal import get_localzone
local_tz = get_localzone()
tz = pytz.timezone(zone=get_localzone())
today = datetime.now(tz=tz)
start = today.replace(hour=0, minute=0, second=0, microsecond=0)
end = start + timedelta(1)
print(start, end)
But I get:
Traceback (most recent call last):
File "/Users/Daniyal/Desktop/Test/Test.py", line 18, in <module>
tz = pytz.timezone(zone=get_localzone())
File "/Users/Daniyal/opt/anaconda3/lib/python3.8/site-packages/pytz/__init__.py", line 163, in timezone
if zone.upper() == 'UTC':
AttributeError: 'America/Toronto' object has no attribute 'upper'
The code is still running for now but I got a error message from PyCharm
Cannot find reference 'reference' in '__init__.pyi'
from pytz import reference
from datetime import datetime
now = datetime.now()
local_time = reference.LocalTimezone()
timezone = local_time.tzname(now)
print(timezone)
pytz==2021.3
>>> import pytz
>>> pytz.timezone('Israel')
<DstTzInfo 'Israel' LMT+2:21:00 STD>
which of course is incorrect, Israel's time zone is +2.
make -C ./tz TOPDIR=pwd
/build USRDIR= USRSHAREDIR=etc install
make[1]: Entering directory '/home/dauren/work/backend/pytz/tz'
awk -v DATAFORM=expr main.zi : '\(.*\).zi'
-f ziguard.awk
africa antarctica asia australasia europe northamerica southamerica etcetera systemv factory backward >main.zi.out
malloc(): memory corruption
Aborted (core dumped)
Makefile:586: recipe for target 'main.zi' failed
make[1]: *** [main.zi] Error 134
make[1]: Leaving directory '/home/dauren/work/backend/pytz/tz'
Makefile:134: recipe for target '.stamp-zoneinfo' failed
make: *** [.stamp-zoneinfo] Error 2
Hi,
I experienced a problem when moving from 2018.4 to 2018.5. I believe that pytz is calculating DST incorrectly since 2018.5. I am using Python 2.7.15. Test Script...
import pytz
from datetime import datetime
print "pytz VERSION", pytz.VERSION
now = datetime.utcnow().replace(tzinfo=pytz.utc)
print "date", now.astimezone(tz=pytz.timezone('Europe/Dublin'))
print "dst", now.astimezone(tz=pytz.timezone('Europe/Dublin')).dst()
Results....
pytz VERSION 2018.5
date 2018-12-17 15:16:17.330781+00:00
dst -1 day, 23:00:00
pytz VERSION 2018.4
date 2018-12-17 15:16:35.487439+00:00
dst 0:00:00
As per the documentation:
common_timezones
is a list of useful, current timezones. It doesn’t contain deprecated zones or historical zones, except for a few I’ve deemed in common usage, such as US/Eastern (open a bug report if you think other timezones are deserving of being included here)
Central European Time is commonly used by all countries in central Europe.
As such, CET should be in common_timezones
In a dynamic deployment environment, sometimes it's needed to "warm" the library by preloading all the data files before the application starts. Would be great if the library had a single entry point for that, to have a shared, stable way of doing so.
Is there a changelog file anywhere that indicates what the changes are in each release? I'm attempting to upgrade from an earlier version but it would be nice to know what has changed.
pytz.all_timezones
ought to return a list of timezones, but it contains strings like CET
and GMT
which aren't timezones, but offsets. They are officially deprecated in the tz database https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
>>> 'CET' in pytz.all_timezones
True
i.e. CET is an offset of +1 relative to UTC
However, the Europe/Berlin
timezone switches between CET and CEST (UTC+2) depending on the time of the year.
A timezone is by established convention not the same thing as an offset:
https://stackoverflow.com/tags/timezone/info
I stumbled on this while trying to use pytz.all_timezones
to validate IANA timezone strings, e.g. Europe/Berlin
.
tz switched the default format from zic -b fat
to zic -b slim
in the 2020b release. The tzfile.py
parser in this project currently does not support this file format and silently chokes on tzfiles generated by the latest tz version, leading to incorrect tzinfo
Python objects that are just using the default UTC time. To future-proof against the Y2038 problem, it would be great if pytz could support the new 64-bit only file format that zic -b slim
produces.
Downstream Arch Linux bug report: FS#68150. Note that Arch patches pytz to use the system timezone database, so this problem doesn't currently appear in a default installation of pytz, which comes bundles with tzfiles generated by an older version of tz. Regardless it would be good to support to add the new file format for the reason outlined above.
Either of the following will error with an OverflowError: date value out of range:
pytz.timezone('Africa/Abidjan').localize(datetime(year=1, month=1, day=1))
pytz.timezone('Africa/Abidjan').localize(datetime(year=9999, month=12, day=31))
where as the outputs should be
respectively
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.