GithubHelp home page GithubHelp logo

zopefoundation / datetime Goto Github PK

View Code? Open in Web Editor NEW
19.0 19.0 23.0 441 KB

This package provides a DateTime data type, as known from Zope. Unless you need to communicate with Zope APIs, you're probably better off using Python's built-in datetime module.

License: Other

Python 100.00%

datetime's People

Contributors

d-maurer avatar dataflake avatar davisagli avatar fdiary avatar georgpfolz avatar hannosch avatar icemac avatar jugmac00 avatar lrowe avatar mauritsvanrees avatar mgedmin avatar perrinjerome avatar philikon avatar strichter avatar thet avatar tseaver avatar vangheem avatar vernans avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datetime's Issues

DateTime 4.5 unit test incompatible with Windows

In the process of updating the DateTime version pin for Zope and running the CI tests I discovered that a recent change is incompatible with Windows. The tests fail with this traceback:

Error in test test_format (DateTime.tests.test_datetime.DateTimeTests)
Traceback (most recent call last):
  File "c:\hostedtoolcache\windows\python\3.6.8\x64\lib\unittest\case.py", line 59, in testPartExecutor
    yield
  File "c:\hostedtoolcache\windows\python\3.6.8\x64\lib\unittest\case.py", line 605, in run
    testMethod()
  File "d:\a\zope\zope\.tox\py36\eggs\datetime-4.5-py3.6.egg\DateTime\tests\test_datetime.py", line 690, in test_format
    result = dt.strftime(fmt)
  File "d:\a\zope\zope\.tox\py36\eggs\datetime-4.5-py3.6.egg\DateTime\DateTime.py", line 1566, in strftime
    microseconds).strftime(format)
ValueError: Invalid format string

The corresponding code is part of #37.

tests fail in 2038

BUG/PROBLEM REPORT / FEATURE REQUEST

What I did:

osc co openSUSE:Factory/python-DateTime && cd $_
osc build --vm-type=kvm --noservice --clean --build-opt=--vm-custom-opt="-rtc base=2039-09-02T06:07:00" --alternative-project=home:bmwiedemann:reproducible openSUSE_Tumbleweed

What I expect to happen:

tests should keep working in the future (at least 16 years)

What actually happened:

similar to issue #41 in that there is a rounding error in DateTime-5.2 that can randomly break a test.

 =================================== FAILURES ===================================
 __________________________ DateTimeTests.test_pickle ___________________________
 
 self = <DateTime.tests.test_datetime.DateTimeTests testMethod=test_pickle>
 
     def test_pickle(self):
         dt = DateTime()
         data = pickle.dumps(dt, 1)
         new = pickle.loads(data)
         for key in DateTime.__slots__:
 >           self.assertEqual(getattr(dt, key), getattr(new, key))
 E           AssertionError: 2198556426235027 != 2198556426235026
 
 src/DateTime/tests/test_datetime.py:253: AssertionError
 =============================== warnings summary ===============================

What version of Python and Zope/Addons I am using:

openSUSE-Tumbleweed-20230729 python3.10

Timezone WAT converts to GMT-1 instead of GMT+1

BUG/PROBLEM REPORT (OR OTHER COMMON ISSUE)

The timezone Africa/Libreville converts to West African Time WAT and results in date objects using GMT-1 instead of GMT+1.

https://github.com/zopefoundation/DateTime/blob/master/src/DateTime/pytz_support.py#L178

What I did:

In my zope.conf I have this TZ setting:

TZ Africa/Libreville

This is the same time that is set on the OS:

root@senaite-test # timedatectl                                                                                                                                                                                         /home/senaite/senaite
                      Local time: Do 2022-02-10 19:57:11 WAT
                  Universal time: Do 2022-02-10 18:57:11 UTC
                        RTC time: Do 2022-02-10 18:57:11
                       Time zone: Africa/Libreville (WAT, +0100)
       System clock synchronized: yes
systemd-timesyncd.service active: yes
                 RTC in local TZ: no

And get converted to WAT:

>>> import time
>>> time.tzname
('WAT', 'WAT')

Although the current time is displayed correct at the time of instantiation:

(Pdb++) DateTime()
DateTime('2022/02/10 21:18:56.073462 GMT-1')

this call shows that it is actually a display (cache?) issue and the time is in UTC-1:

(Pdb++) DateTime().strftime("%H")
'19'

I believe that this is an error between the POSIX style notation and the GMT timezone that DateTime uses.

The Olson tz database defines Etc/GMT+N timezones which conform with the POSIX style:

Those zone names beginning with "Etc/GMT" have their sign reversed from the
standard ISO 8601 convention. In the "Etc" area, zones west of GMT have a
positive sign and those east have a negative sign in their name (e.g
"Etc/GMT-14" is 14 hours ahead of GMT.)

https://en.wikipedia.org/wiki/Tz_database

What I expect to happen:

The timezone WAT should be UTC+1

What actually happened:

The timezone WAT is UTC-1

What version of Python and Zope/Addons I am using:

  • Ubuntu 18.04
  • Plone 5.2.7 (5215)
  • CMF 2.5.4
  • Zope 4.6.3
  • Python 2.7.17 (default, Feb 25 2021, 14:02:55) [GCC 7.5.0]
  • PIL 6.2.2 (Pillow)
  • WSGI: On
  • Server: waitress 1.4.4

Error in unpickling DateTime object having '+NNNN' timezone

Hi,

We cannot unpickle the pickled result of a DateTime object having '+NNNN' timezone.

With 4.1, it is possible for +0300, but not possible for +0430 (Afghanistan timezone).

>>> from DateTime import DateTime
>>> a=DateTime('2007/01/02 12:34:56.789 +0300')
>>> a._tz
'GMT+3'
>>> a._timezone_naive
False
>>> a.tzoffset()
10800
>>> b = DateTime()
>>> b.__setstate__(a.__getstate__())
>>> b._tz
'GMT+3'
>>> a == b
True
>>> a=DateTime('2007/01/02 12:34:56.789 +0430')
>>> a._tz
'+0430'
>>> a._timezone_naive
True
>>> a.tzoffset()
16200
>>> b = DateTime()
>>> b.__setstate__(a.__getstate__())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/DateTime/DateTime.py", line 458, in __setstate__
    self._parse_args(value[0], value[2])
  File "/path/to/DateTime/DateTime.py", line 789, in _parse_args
    tz = _TZINFO._zmap[tz.lower()]
KeyError: '+0430'

With 3.0.3, it is not possible even for +0300.

>>> from DateTime import DateTime
>>> a=DateTime('2007/01/02 12:34:56.789 +0300')
>>> a._tz
'+0300'
>>> a._timezone_naive
True
>>> a.__getstate__()
(1167730496.789, True, '+0300')
>>> a.tzoffset()
10800
>>> b = DateTime()
>>> b.__setstate__(a.__getstate__())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/path/to/DateTime/DateTime.py", line 455, in __setstate__
    self._parse_args(value[0], value[2])
  File "/path/to/DateTime/DateTime.py", line 787, in _parse_args
    tz = _TZINFO._zmap[tz.lower()]
KeyError: '+0300'

With DateTime 2.12.8, it is possible for both +0300 and +0430.

>>> from DateTime import DateTime
>>> a = DateTime('2007/01/02 12:34:56.789 +0300')
>>> a._tz
'+0300'
>>> a._timezone_naive
True
>>> a.tzoffset()
10800
>>> b = DateTime()
>>> b.__setstate__(a.__dict__) # using __dict__ as there is not __getstate__() in 2.12.8
>>> b._tz
'+0300'
>>> a == b
True
>>> a = DateTime('2007/01/02 12:34:56.789 +0430')
>>> a._tz
'+0430'
>>> a._timezone_naive
True
>>> a.tzoffset()
16200
>>> b = DateTime()
>>> b.__setstate__(a.__dict__) # using __dict__ as there is not __getstate__() in 2.12.8
>>> b._tz
'+0430'
>>> a == b
True

Inconsistent localization to timezones

while testing timezone handling in plone.app.event i stumbled upon this inconsistency.

Timezone-naive DateTime objects have the same .ISO() value but behave differently when localized to UTC:

>>> unaware = DateTime('2016-06-15T07:00:00')
>>> unaware.timezoneNaive()
True
>>> unaware2=DateTime('2016/06/15 07:00:00')
>>> unaware2.ISO()
'2016-06-15T07:00:00'
>>> unaware.ISO() == unaware2.ISO()
True

>>> unaware2.toZone('UTC').ISO()
'2016-06-15T05:00:00+00:00'

>>> unaware.toZone('UTC').ISO()
'2016-06-15T07:00:00+00:00'

can this difference be explained somehow or is this a bug?

error DatetimeProperties' object has no attribute 'week'

BUG/PROBLEM REPORT / FEATURE REQUEST

I reinstalled windows, and since then, I get allways this same error:


Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\threading.py", line 980, in _bootstrap_inner
    self.run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\jsgas\OneDrive\Trading\SteUi\SteUi_Junior\SteUi_Jr.py", line 1374, in test
    fastai.tabular.add_datepart(df2, 'time', drop='True')
  File "C:\Users\jsgas\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\fastai\tabular\transform.py", line 63, in add_datepart
    for n in attr: df[prefix + n] = getattr(field.dt, n.lower())
AttributeError: 'DatetimeProperties' object has no attribute 'week'

What I did:

What I expect to happen: this error didnt appear yesturday

What actually happened: just reinstalled windows

What version of Python and Zope/Addons I am using: 3.9.13

win11

Two or one digit number format of time results in different time zones

Hi,
we observed an odd behaviour of time string parsing

Example:

    from DateTime import DateTime
    t1 = DateTime('2016-04-21 13:05')
    t2 = DateTime('2016-04-21 13:5')
    assert (t1 == t2), '%s is not equal to %s' % (t1, t2)

results in
Traceback (most recent call last):
File "", line 1, in
AssertionError: 2016/04/21 13:05:00 GMT+0 is not equal to 2016/04/21 13:05:00 GMT+2

In summary, one digit number for hour, minute or second always returns TZ GMT+0. Two digit number format of time (hh:mm:ss) returns local TZ. Is this a bug or feature?

supporting fstring formatting

It would be great if DateTime could support the new fstring formatting like datetime already does:

import datetime, DateTime
for now in (datetime.datetime.now(), DateTime.DateTime()):
    try:
        print(type(now), f'{now = :%-d.%-m.%Y %H:%M}')
    except TypeError as e:
        print(type(now), e)

prints -->

<class 'datetime.datetime'> now = 26.5.2022 05:45
<class 'DateTime.DateTime.DateTime'> unsupported format string passed to DateTime.__format__

tests fail after 2038-01-10

BUG/PROBLEM REPORT (OR OTHER COMMON ISSUE)

What I did:

run tests on 2038-01-10
on openSUSE, I do

osc co openSUSE:Factory/python-DateTime && cd $_
osc build --vm-type=kvm --noservice --clean --build-opt=--vm-custom-opt="-rtc base=2038-01-10T00:00:00" --alternative-project=home:bmwiedemann:reproducible openSUSE_Tumbleweed

What I expect to happen:

tests should continue to pass in future

What actually happened:

3 tests failed:

     def testAddPrecision(self):  
         # Precision of serial additions
         dt = DateTime()          
 >       self.assertEqual(str(dt + 0.10 + 3.14 + 6.76 - 10), str(dt),
                          dt)              
 E       AssertionError: '2038/10/07 08:52:44.959838 UTC' != '2038/10/07 08:52:44.959840 UTC'    
 E       - 2038/10/07 08:52:44.959838 UTC
 E       ?                         ^^
 E       + 2038/10/07 08:52:44.959840 UTC
 E       ?                         ^^
 E        : 2038/10/07 08:52:44.959840 UTC

 FAILED src/DateTime/tests/test_datetime.py::DateTimeTests::testAddPrecision
 FAILED src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor4
 FAILED src/DateTime/tests/test_datetime.py::DateTimeTests::testSubtraction - ...

What version of Python and Zope/Addons I am using:

openSUSE-Tumbleweed 20220907
python-3.8

anaconda cloud package?

Hello,

DateTime is a great package however only pypi distibution is present and it is not possible for anyone to use this package in a project if they want to to publish their project to anaconda cloud. Do you have any intentions of publishing this project to anaconda cloud?

DateTime 2.12 gives test failure with pytz 2017.3

Seen on Travis and locally when running tests for zopefoundation/Zope#226:

Failure in test testLegacyTimezones (DateTime.tests.testDateTime.DateTimeTests)
Traceback (most recent call last):
  File "/opt/python/2.7.13/lib/python2.7/unittest/case.py", line 329, in run
    testMethod()
  File "/home/travis/build/zopefoundation/Zope/eggs/DateTime-2.12.8-py2.7.egg/DateTime/tests/testDateTime.py", line 667, in testLegacyTimezones
    self.failUnless(name.lower() in cache._zidx, 'legacy timezone  %s cannot be looked up' % name)
  File "/opt/python/2.7.13/lib/python2.7/unittest/case.py", line 612, in deprecated_func
    return original_func(*args, **kwargs)
  File "/opt/python/2.7.13/lib/python2.7/unittest/case.py", line 422, in assertTrue
    raise self.failureException(msg)
AssertionError: legacy timezone  Canada/East-Saskatchewan cannot be looked up

With pytz 2017.2 the test passes, with 2017.3 it fails.
The tests currently get DateTime version 2.12.8, which is the latest in the 2.12.x branch.

build broken for pypy

https://travis-ci.org/zopefoundation/DateTime/jobs/529765018

$ python --version
Python 2.7.13 (c925e7381036, Jun 05 2017, 21:20:51)
[PyPy 5.8.0 with GCC 6.2.0 20160901]
$ pip --version
pip 9.0.1 from /home/travis/virtualenv/pypy2.7-5.8.0/site-packages (python 2.7)
install.1
4.50s$ pip install coverage coveralls
Collecting coverage
Collecting coveralls
  Using cached https://files.pythonhosted.org/packages/10/b6/f60e90515658a61e18d5769ed9ca0a8b6a9a95a432d7d40328dd16754087/coveralls-1.7.0-py2.py3-none-any.whl
Collecting docopt>=0.6.1 (from coveralls)
Collecting requests>=1.0.0 (from coveralls)
  Using cached https://files.pythonhosted.org/packages/7d/e3/20f3d364d6c8e5d2353c72a67778eb189176f08e873c9900e10c0287b84b/requests-2.21.0-py2.py3-none-any.whl
Collecting urllib3[secure]; python_version < "3" (from coveralls)
  Downloading https://files.pythonhosted.org/packages/39/ec/d93dfc69617a028915df914339ef66936ea976ef24fa62940fd86ba0326e/urllib3-1.25.2-py2.py3-none-any.whl (150kB)
    100% |████████████████████████████████| 153kB 3.8MB/s 
Collecting chardet<3.1.0,>=3.0.2 (from requests>=1.0.0->coveralls)
  Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl
Collecting idna<2.9,>=2.5 (from requests>=1.0.0->coveralls)
  Using cached https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests>=1.0.0->coveralls)
  Using cached https://files.pythonhosted.org/packages/60/75/f692a584e85b7eaba0e03827b3d51f45f571c2e793dd731e598828d380aa/certifi-2019.3.9-py2.py3-none-any.whl
Collecting pyOpenSSL>=0.14; extra == "secure" (from urllib3[secure]; python_version < "3"->coveralls)
  Using cached https://files.pythonhosted.org/packages/01/c8/ceb170d81bd3941cbeb9940fc6cc2ef2ca4288d0ca8929ea4db5905d904d/pyOpenSSL-19.0.0-py2.py3-none-any.whl
Collecting cryptography>=1.3.4; extra == "secure" (from urllib3[secure]; python_version < "3"->coveralls)
Collecting ipaddress; python_version == "2.7" and extra == "secure" (from urllib3[secure]; python_version < "3"->coveralls)
  Using cached https://files.pythonhosted.org/packages/fc/d0/7fc3a811e011d4b388be48a0e381db8d990042df54aa4ef4599a31d39853/ipaddress-1.0.22-py2.py3-none-any.whl
Requirement already satisfied: six>=1.5.2 in /home/travis/virtualenv/pypy2.7-5.8.0/site-packages (from pyOpenSSL>=0.14; extra == "secure"->urllib3[secure]; python_version < "3"->coveralls)
Collecting asn1crypto>=0.21.0 (from cryptography>=1.3.4; extra == "secure"->urllib3[secure]; python_version < "3"->coveralls)
  Using cached https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a510576f1a56d1e0a7ad7bd8ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl
Requirement already satisfied: cffi!=1.11.3,>=1.8 in /opt/python/pypy2.7-5.8.0/lib_pypy (from cryptography>=1.3.4; extra == "secure"->urllib3[secure]; python_version < "3"->coveralls)
Collecting enum34; python_version < "3" (from cryptography>=1.3.4; extra == "secure"->urllib3[secure]; python_version < "3"->coveralls)
  Using cached https://files.pythonhosted.org/packages/c5/db/e56e6b4bbac7c4a06de1c50de6fe1ef3810018ae11732a50f15f62c7d050/enum34-1.1.6-py2-none-any.whl
Installing collected packages: coverage, docopt, chardet, idna, asn1crypto, enum34, ipaddress, cryptography, pyOpenSSL, certifi, urllib3, requests, coveralls
Successfully installed asn1crypto-0.24.0 certifi-2019.3.9 chardet-3.0.4 coverage-4.5.3 coveralls-1.7.0 cryptography-2.6.1 docopt-0.6.2 enum34-1.1.6 idna-2.8 ipaddress-1.0.22 pyOpenSSL-19.0.0 requests-2.21.0 urllib3-1.25.2
install.2
1.03s$ pip install zc.buildout
Collecting zc.buildout
  Using cached https://files.pythonhosted.org/packages/da/7e/f8174cafc7616ddc7230c4cb1f2e39efffcb7be110d49d50d2ff9709ebef/zc.buildout-2.13.1-py2.py3-none-any.whl
Requirement already satisfied: setuptools>=8.0 in /home/travis/virtualenv/pypy2.7-5.8.0/site-packages (from zc.buildout)
Installing collected packages: zc.buildout
Successfully installed zc.buildout-2.13.1
install.3
1.19s$ buildout bootstrap
Creating directory '/home/travis/build/zopefoundation/DateTime/bin'.
Creating directory '/home/travis/build/zopefoundation/DateTime/parts'.
Creating directory '/home/travis/build/zopefoundation/DateTime/develop-eggs'.
Generated script '/home/travis/build/zopefoundation/DateTime/bin/buildout'.
11.50s$ buildout
Develop: '/home/travis/build/zopefoundation/DateTime/.'
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '*.pyo' found anywhere in distribution
Getting distribution for 'zope.testrunner==5.0'.
package init file 'src/zope/testrunner/tests/testrunner-ex/__init__.py' not found (or not a regular file)
  File "build/bdist.linux-x86_64/egg/zope/testrunner/tests/testrunner-ex/sample2/badsyntax.py", line 16
    importx unittest
           ^
SyntaxError: invalid syntax
  File "/home/travis/build/zopefoundation/DateTime/eggs/tmpqc7s_O/zope.testrunner-5.0-py2.7.egg/zope/testrunner/tests/testrunner-ex/sample2/badsyntax.py", line 16
    importx unittest
           ^
SyntaxError: invalid syntax
Got zope.testrunner 5.0.
Installing interpreter.
Getting distribution for 'tox==3.9.0'.
/opt/python/pypy2.7-5.8.0/lib-python/2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'use_scm_version'
  warnings.warn(msg)
warning: no files found matching 'CHANGELOG.rst'
warning: no files found matching 'README.rst'
warning: no previously-included files matching '__pycache__' found anywhere in distribution
warning: no previously-included files matching '*.py[cod]' found anywhere in distribution
zip_safe flag not set; analyzing archive contents...
tox._pytestplugin: module references __file__
tox.constants: module references __file__
tox.config.__init__: module references __file__
tox.session.__init__: module references __file__
While:
  Installing interpreter.
  Getting distribution for 'tox==3.9.0'.
An internal error occurred due to a bug in either zc.buildout or in a
recipe being used:
Traceback (most recent call last):
  File "/home/travis/virtualenv/pypy2.7-5.8.0/site-packages/zc/buildout/buildout.py", line 2174, in main
    getattr(buildout, command)(args)
  File "/home/travis/virtualenv/pypy2.7-5.8.0/site-packages/zc/buildout/buildout.py", line 817, in install
    installed_files = self[part]._call(recipe.install)
  File "/home/travis/virtualenv/pypy2.7-5.8.0/site-packages/zc/buildout/buildout.py", line 1603, in _call
    return f()
  File "/home/travis/build/zopefoundation/DateTime/eggs/zc.recipe.egg-2.0.7-py2.7.egg/zc/recipe/egg/egg.py", line 227, in install
    reqs, ws = self.working_set()
  File "/home/travis/build/zopefoundation/DateTime/eggs/zc.recipe.egg-2.0.7-py2.7.egg/zc/recipe/egg/egg.py", line 87, in working_set
    allow_unknown_extras=bool_option(buildout_section, 'allow-unknown-extras')
  File "/home/travis/build/zopefoundation/DateTime/eggs/zc.recipe.egg-2.0.7-py2.7.egg/zc/recipe/egg/egg.py", line 168, in _working_set
    allow_unknown_extras=allow_unknown_extras)
  File "/home/travis/virtualenv/pypy2.7-5.8.0/site-packages/zc/buildout/easy_install.py", line 957, in install
    return installer.install(specs, working_set)
  File "/home/travis/virtualenv/pypy2.7-5.8.0/site-packages/zc/buildout/easy_install.py", line 682, in install
    for dist in self._get_dist(requirement, ws):
  File "/home/travis/virtualenv/pypy2.7-5.8.0/site-packages/zc/buildout/easy_install.py", line 574, in _get_dist
    dists = [_move_to_eggs_dir_and_compile(dist, self._dest)]
  File "/home/travis/virtualenv/pypy2.7-5.8.0/site-packages/zc/buildout/easy_install.py", line 1771, in _move_to_eggs_dir_and_compile
    assert newdist is not None  # newloc above is missing our dist?!
AssertionError
The command "buildout" failed and exited with 1 during .
Your build has been stopped.

Any hint how to fix this?

why DateTime(0).equalTo(None) is True ?

BUG/PROBLEM REPORT / FEATURE REQUEST

DateTime(0).equalTo(None) behaviour is different between DateTime 2 and DateTime 4+.

With DateTime 2

>>> from DateTime import DateTime
>>> DateTime(0).equalTo(None)
False

With DateTime 4+

>>> from DateTime import DateTime
>>> DateTime(0).equalTo(None)
True

It is caused by commit b9ddd8b where equalTo(None) is treated like equalTo(0) as 'further py3k work' (and same for greaterThanEqualTo and lessThanEqualTo). But if the intention is to accept comparing with None like Python 2, None is always the first in Python 2 sort, thus the implementation should be rather the following.

def equalTo(self, t):
  if t is None:
    return False # instead of 't = 0'
  ...

def greaterThanEqualTo(self, t):
  if t is None:
    return True # instead of 't = 0'
  ...

def lessThanEqualTo(self, t):
  if t is None:
    return False # instead of 't = 0'
  ...

For your reference, the interface docstring is the following, where I see no reason to treat None as DateTime(0)

Compare this DateTime object to another DateTime object OR
a floating point number such as that which is returned by the
python time module. Returns true if the object represents a
date/time equal to the specified DateTime or time module style
time. Revised to give more correct results through comparison
of long integer milliseconds.

What do you think ?

implicit datefmt

I stumbled upon this when trying to create a DateTime object like this: DateTime.DateTime('2.4.2022'). The result was "DateTime('2022/02/04 00:00:00 GMT+1')" instead of "DateTime('2022/04/02 00:00:00 GMT+2')".

First I only saw the difference in the timezone, but obviously the date string is interpreted differently than I expected.

I realize that the correct way to create the object would have been DateTime.DateTime('2.4.2022', datefmt='international').

I'm from Austria, so I don't know exactly how dates are used in the US, but according to wikipedia it seems the notation with dots is not used for m/d/Y notation.

Wouldn't it be logical to assume the international order (d.m.Y) for strings with dots rather than the US-based order? (even if the argument datefmt is not passed explicitly)

asdatetime regression in DateTime 4.7 for Python 2.7

When using the latest DateTime in Plone 5.2 on Python 2.7, one test fails. See plone/Products.ATContentTypes#69
Note that this is a package that only works on Python 2.7.

The regression is caused by the changes in 4.7 from PR #42. I am preparing a PR. Looks like it only goes wrong in Python 2, not Python 3.

Small problem: @icemac has just changed DateTime master to be for Python 3 only.
So I have created branch 4.x from right before his changes. I will make my PR against that new branch.

`DateTime.DateTime.equalTo` now breaks with string argument

BUG/PROBLEM REPORT / FEATURE REQUEST

Since DateTime 5.2, using DateTime.DateTime.equalTo with something else than a DateTime or a number throws AttributeError. This is a regression from #54 ( cc @fdiary )

What I did:

>>> import DateTime
>>> DateTime.DateTime() == ""
False
>>> DateTime.DateTime().equalTo("")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "./DateTime/src/DateTime/DateTime.py", line 1295, in equalTo
    return self._micros == t._micros
AttributeError: 'str' object has no attribute '_micros'

What I expect to happen:

DateTime.DateTime().equalTo("") should be False

What actually happened:

AttributeError: 'str' object has no attribute '_micros'

What version of Python and Zope/Addons I am using:

This is current master branch 955f3b9

`pytz.exceptions.UnknownTimeZoneError` when unpickling `DateTime.DateTime('GMT+1').asdatetime()`

BUG/PROBLEM REPORT / FEATURE REQUEST

What I did:

DateTime.asdatetime converts to datetime carrying the same date, including timezone, but such datetimes cannot be pickled:

>>> import DateTime, pickle; pickle.loads(pickle.dumps(DateTime.DateTime('GMT+1').asdatetime()))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/srv/slapgrid/slappart30/srv/project/zope/venv/lib/python3.9/site-packages/pytz/__init__.py", line 307, in _p
    return unpickler(*args)
  File "/srv/slapgrid/slappart30/srv/project/zope/venv/lib/python3.9/site-packages/pytz/tzinfo.py", line 542, in unpickler
    tz = pytz.timezone(zone)
  File "/srv/slapgrid/slappart30/srv/project/zope/venv/lib/python3.9/site-packages/pytz/__init__.py", line 188, in timezone
    raise UnknownTimeZoneError(zone)
pytz.exceptions.UnknownTimeZoneError: 'GMT+1'

What I expect to happen:

the datetime instance can be unpickled

What actually happened:

an UnknownTimeZoneError is raised

What version of Python and Zope/Addons I am using:

pytz 2023.3.post1
DateTime current master branch ( 3104882 )

More information:

DateTime constructs its own timezones with GMT+1 names that are defined here:

_numeric_timezone_data = {
'GMT': ('GMT', 0, 1, [], '', [(0, 0, 0)], 'GMT\000'),
'GMT+0': ('GMT+0', 0, 1, [], '', [(0, 0, 0)], 'GMT+0000\000'),
'GMT+1': ('GMT+1', 0, 1, [], '', [(3600, 0, 0)], 'GMT+0100\000'),

and used to create a registry with instances of a subclass of pytz.tzinfo.StaticTzInfo here:

def _static_timezone_factory(data):
zone = data[0]
cls = type(zone, (StaticTzInfo,), dict(
zone=zone,
_utcoffset=memorized_timedelta(data[5][0][0]),
_tzname=data[6][:-1])) # strip the trailing null
return cls()
_numeric_timezones = {key: _static_timezone_factory(data)
for key, data in _numeric_timezone_data.items()}

unpickling such an instance is causing the UnknownTimeZoneError exception, because pytz.tzinfo.StaticTzInfo defines __reduce__ which calls _p, which is just a wrapper calling unpickler which basically does this:

def unpickler(zone):
    ...
    if zone not in _tzinfo_cache:
        if zone in all_timezones_set:  # noqa
            fp = open_resource(zone)
            try:
                _tzinfo_cache[zone] = build_tzinfo(zone, fp)
            finally:
                fp.close()
        else:
            raise UnknownTimeZoneError(zone)

where the UnknownTimeZoneError is raised.

I believe the fix can be to adjust _static_timezone_factory to create classes with a __reduce__ understanding the extra timezones from DateTime.pytz_support, I'm preparing a patch.

date only

Something I often need is to convert a DateTime object to a date. This is pretty easy with the lowercase datetime class (just convert to datetime.date). With DateTime, I set the time to 00:00:00, but that's it's a bit complicated if it's meant to be timezone-safe (without changing the timezone).

Here's what I've been coming up with:

dt = DateTime()
date = dt - (dt + dt.tzoffset() / 24 / 3600)

What do you think about adding a new method date or toDate to the class? (and maybe also a method today)

I would be willing to provide a PR :)

Bug report getting timezone

I tried DateTime version 4.3 on Python 3.7.
I found bug for DateTime parser.

>>> import sys
>>> sys.version
'3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) \n[Clang 6.0 (clang-600.0.57)]'
>>> from DateTime import DateTime
>>> DateTime("2019-11-9 10:00:00")
DateTime('2019/11/09 10:00:00 GMT+9')
>>> DateTime("2019-11-19 10:00:00")
DateTime('2019/11/19 10:00:00 GMT+0')
>>> DateTime("2019-11-09 10:00:00")
DateTime('2019/11/09 10:00:00 GMT+0')

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.