Giter Site home page Giter Site logo

dateutil's Introduction

dateutil - powerful extensions to datetime

pypi version supported Python version licence

Join the chat at https://gitter.im/dateutil/dateutil Read the documentation at https://dateutil.readthedocs.io/en/latest/

travis build status appveyor build status Code coverage

The dateutil module provides powerful extensions to the standard datetime module, available in Python.

Installation

dateutil can be installed from PyPI using pip (note that the package name is different from the importable name):

pip install python-dateutil

Download

dateutil is available on PyPI https://pypi.org/project/python-dateutil/

The documentation is hosted at: https://dateutil.readthedocs.io/en/stable/

Code

The code and issue tracker are hosted on GitHub: https://github.com/dateutil/dateutil/

Features

  • Computing of relative deltas (next month, next year, next Monday, last week of month, etc);
  • Computing of relative deltas between two given date and/or datetime objects;
  • Computing of dates based on very flexible recurrence rules, using a superset of the iCalendar specification. Parsing of RFC strings is supported as well.
  • Generic parsing of dates in almost any string format;
  • Timezone (tzinfo) implementations for tzfile(5) format files (/etc/localtime, /usr/share/zoneinfo, etc), TZ environment string (in all known formats), iCalendar format files, given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, UTC timezone, and Windows registry-based time zones.
  • Internal up-to-date world timezone information based on Olson's database.
  • Computing of Easter Sunday dates for any given year, using Western, Orthodox or Julian algorithms;
  • A comprehensive test suite.

Quick example

Here's a snapshot, just to give an idea about the power of the package. For more examples, look at the documentation.

Suppose you want to know how much time is left, in years/months/days/etc, before the next easter happening on a year with a Friday 13th in August, and you want to get today's date out of the "date" unix system command. Here is the code:

readmeexample

>>> from dateutil.relativedelta import * >>> from dateutil.easter import * >>> from dateutil.rrule import * >>> from dateutil.parser import * >>> from datetime import * >>> now = parse("Sat Oct 11 17:13:46 UTC 2003") >>> today = now.date() >>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year >>> rdelta = relativedelta(easter(year), today) >>> print("Today is: %s" % today) Today is: 2003-10-11 >>> print("Year with next Aug 13th on a Friday is: %s" % year) Year with next Aug 13th on a Friday is: 2004 >>> print("How far is the Easter of that year: %s" % rdelta) How far is the Easter of that year: relativedelta(months=+6) >>> print("And the Easter of that year is: %s" % (today+rdelta)) And the Easter of that year is: 2004-04-11

Being exactly 6 months ahead was really a coincidence :)

Contributing

We welcome many types of contributions - bug reports, pull requests (code, infrastructure or documentation fixes). For more information about how to contribute to the project, see the CONTRIBUTING.md file in the repository.

Author

The dateutil module was written by Gustavo Niemeyer <[email protected]> in 2003.

It is maintained by:

Starting with version 2.4.1 and running until 2.8.2, all source and binary distributions will be signed by a PGP key that has, at the very least, been signed by the key which made the previous release. A table of release signing keys can be found below:

Releases Signing key fingerprint
2.4.1-2.8.2 6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB

New releases may have signed tags, but binary and source distributions uploaded to PyPI will no longer have GPG signatures attached.

Contact

Our mailing list is available at [email protected]. As it is hosted by the PSF, it is subject to the PSF code of conduct.

License

All contributions after December 1, 2017 released under dual license - either Apache 2.0 License or the BSD 3-Clause License. Contributions before December 1, 2017 - except those those explicitly relicensed - are released only under the BSD 3-Clause License.

dateutil's People

Stargazers

 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  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

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

dateutil's Issues

Allow to use system zoneinfo

Dateutil should use system zoneinfo (available in /usr/share/zoneinfo) when dateutil-zoneinfo.tar.gz is not available.

--- dateutil/zoneinfo/__init__.py
+++ dateutil/zoneinfo/__init__.py
@@ -14,9 +14,10 @@

 __all__ = ["setcachesize", "gettz", "rebuild"]

-_ZONEFILENAME = "dateutil-zoneinfo.tar.gz"
+_LOCAL_ZONEINFO_FILE = "dateutil-zoneinfo.tar.gz"
+_SYSTEM_ZONEINFO_DIR = "/usr/share/zoneinfo"

-# python2.6 compatability. Note that TarFile.__exit__ != TarFile.close, but
+# python2.6 compatibility. Note that TarFile.__exit__ != TarFile.close, but
 # it's close enough for python2.6
 _tar_open = TarFile.open
 if not hasattr(TarFile, '__exit__'):
@@ -31,9 +32,8 @@

 def getzoneinfofile_stream():
     try:
-        return BytesIO(get_data(__name__, _ZONEFILENAME))
+        return BytesIO(get_data(__name__, _LOCAL_ZONEINFO_FILE))
     except IOError as e:  # TODO  switch to FileNotFoundError?
-        warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror))
         return None


@@ -59,6 +59,14 @@
                 self.zones.update(links)
         else:
             self.zones = dict()
+            if os.path.isdir(_SYSTEM_ZONEINFO_DIR):
+                for root, dirnames, filenames in os.walk(_SYSTEM_ZONEINFO_DIR):
+                    for filename in filenames:
+                        absolute_filename = os.path.join(root, filename)
+                        relative_filename = absolute_filename[len(_SYSTEM_ZONEINFO_DIR)+1:]
+                        with open(absolute_filename, "rb") as file:
+                            if file.read(4) == b"TZif":
+                                self.zones[relative_filename] = tzfile(absolute_filename, relative_filename)


 # The current API has gettz as a module function, although in fact it taps into
@@ -99,7 +107,7 @@
                         "libc-bin or some other package that provides it, "
                         "or it's not in your PATH?")
                     raise
-        target = os.path.join(moduledir, _ZONEFILENAME)
+        target = os.path.join(moduledir, _LOCAL_ZONEINFO_FILE)
         with _tar_open(target, "w:%s" % format) as tf:
             for entry in os.listdir(zonedir):
                 entrypath = os.path.join(zonedir, entry)

Add weeks argument to relativedelta

Migrating issue from launchpad issue #727525.

You can read the full exchange there, but the gist is that while there's a keyword for "weeks" in relativedelta, you cannot retrieve the number of weeks in a relativedelta object as you can for the other time periods.

The solution would be to offer a weeks property that returns self.days // 7. Seems reasonable.

Tests failing for me on OS X

$ tox -e py27
GLOB sdist-make: /Users/marca/dev/git-repos/dateutil/setup.py
py27 inst-nodeps: /Users/marca/dev/git-repos/dateutil/.tox/dist/python-dateutil-2.3.zip
py27 runtests: PYTHONHASHSEED='3995892525'
py27 runtests: commands[0] | python setup.py test -q
running test
running egg_info
writing dependency_links to python_dateutil.egg-info/dependency_links.txt
writing top-level names to python_dateutil.egg-info/top_level.txt
writing python_dateutil.egg-info/PKG-INFO
writing requirements to python_dateutil.egg-info/requires.txt
reading manifest file 'python_dateutil.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'python_dateutil.egg-info/SOURCES.txt'
running build_ext
................................................................................................................................................................................................................................................................................................................................................................................................................................................................................/Users/marca/dev/git-repos/dateutil/dateutil/zoneinfo/__init__.py:36: UserWarning: I/O error(2): No such file or directory
  warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror))
........s..................FFF
======================================================================
FAIL: testZoneInfoFileEnd1 (dateutil.test.test.TZTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/marca/dev/git-repos/dateutil/dateutil/test/test.py", line 3956, in testZoneInfoFileEnd1
    self.assertEqual(datetime(2003, 10, 26, 0, 59, tzinfo=tz).tzname(), "EDT")
AssertionError: None != u'EDT'

======================================================================
FAIL: testZoneInfoFileStart1 (dateutil.test.test.TZTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/marca/dev/git-repos/dateutil/dateutil/test/test.py", line 3951, in testZoneInfoFileStart1
    self.assertEqual(datetime(2003, 4, 6, 1, 59, tzinfo=tz).tzname(), "EST")
AssertionError: None != u'EST'

======================================================================
FAIL: testZoneInfoOffsetSignal (dateutil.test.test.TZTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/marca/dev/git-repos/dateutil/dateutil/test/test.py", line 3962, in testZoneInfoOffsetSignal
    self.assertNotEqual(utc, None)
AssertionError: None == None

----------------------------------------------------------------------
Ran 494 tests in 0.474s

FAILED (failures=3, skipped=1)
ERROR: InvocationError: '/Users/marca/dev/git-repos/dateutil/.tox/py27/bin/python setup.py test -q'
___________________________________________________________________________________ summary ____________________________________________________________________________________
ERROR:   py27: commands failed

Any ideas?

Incorrect timezone during PDT -> PST Switch

Migrated from launchpad issue #1390262:

Quoting Yupeng on 2014-11-07:

root@yupeng-desktop:~# date
Sun Nov 2 01:43:42 PDT 2014
root@yupeng-desktop:~# python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import *
>>> from dateutil.tz import *
>>> datetime.now(tzlocal()).tzname()
'PST'

Parser needs more extensive documentation

After seeing Issues #25 and #21, it's pretty clear that parser needs some better documentation about edge cases and how things are going to fall back. I'm worried that we're creating an unlikely situation where people might start relying on undocumented behavior. I'm going to take a crack at #25 and when I do that I'll also try to add basic documentation.

I'm going to start with the basics and the fallback conditions. If there's anything else that's in desperate need of documentation, please let me know (or write it and make a PR and it can be merged with my docstring mods)!

Add ability to convert datetime to Unix timestamp

I have a utility function to map a datetime to a Unix timestamp but this use case is common enough to have it in a library (preferably dateutil or pytz as these are very common Python datetime dependencies).

Searching online I can see that this comes up often enough that multiple approaches were coined. The first doesn't require additional dependencies, the second approach does depend on pytz:

>>> import calendar;
>>> calendar.timegm(d.utctimetuple())
>>> int((datetime_obj - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC)).total_seconds())

Is this something that would be useful in this library? The key thing is that neither of the above approaches expresses the idea in an "obvious" enough way to duplicate it across your codebase and a utility function would be desirable anyhow.

Memory usage by dateutil.zoneinfo increased significantly from 2.2 to 2.3

From change log of version 2.3:

  • Changed many aspects of dealing with the zone info file. Instead of a cache,
    all the zones are loaded to memory, but symbolic links are loaded only once,
    so not much memory is used.

As of 2.3 zoneinfo loads all the timezones from tar file in memory once and keeps it there.
I used this script to check the implication of this:

#!/usr/bin/env python
import resource
import gc

def memory_usage_mb():
    return float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) / (1024 * 1024)

mem1 = memory_usage_mb()
print "Memory used before zoneinfo.gettz(): {0:.2f}Mb".format(mem1)
from dateutil import zoneinfo
zoneinfo.gettz('America/Los_Angeles')
gc.collect()
mem2 = memory_usage_mb()
print "Memory used after zoneinfo.gettz(): {0:.2f}Mb".format(mem2)
print "Delta: {0:.2f}Mb".format(mem2 - mem1)

shell output

$ git co 2.1
$ ./test_memory
Memory used before zoneinfo.gettz(): 3.86Mb
Memory used after zoneinfo.gettz(): 6.10Mb
Delta: 2.24Mb

$ git co 2.4.2
$ ./test_memory
Memory used before zoneinfo.gettz(): 3.83Mb
Memory used after zoneinfo.gettz(): 10.60Mb
Delta: 6.77Mb

Probably reason behind this was to save time on reading from tar file, which maybe very practical if in one script zoneinfo.gettz() is used often.

On the other hand, if in web environment one web worker maybe running multiple processes and adding memory overhead even 5Mb may affect the max number of processes that can be handled by 1 web worker, especially if system timezones are sufficient and zoneinfo.gettz() is not being used often.

Maybe as a compromise an additional config value can be added to specify the behavior.

"ImportError: cannot import name _thread" with v2.3 on OS X

I'm getting the following error with version 2.3, whereas 2.2 works fine.

Traceback (most recent call last):
  File "/my/path/to/script/my_script.py", line 15, in <module>
    import matplotlib.pyplot as plt
  File "/Library/Python/2.7/site-packages/matplotlib/pyplot.py", line 34, in <module>
    from matplotlib.figure import Figure, figaspect
  File "/Library/Python/2.7/site-packages/matplotlib/figure.py", line 40, in <module>
    from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
  File "/Library/Python/2.7/site-packages/matplotlib/axes/__init__.py", line 4, in <module>
    from ._subplots import *
  File "/Library/Python/2.7/site-packages/matplotlib/axes/_subplots.py", line 10, in <module>
    from matplotlib.axes._axes import Axes
  File "/Library/Python/2.7/site-packages/matplotlib/axes/_axes.py", line 22, in <module>
    import matplotlib.dates as _  # <-registers a date unit converter
  File "/Library/Python/2.7/site-packages/matplotlib/dates.py", line 126, in <module>
    from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
  File "/Library/Python/2.7/site-packages/dateutil/rrule.py", line 14, in <module>
    from six.moves import _thread
ImportError: cannot import name _thread

Add Appveyor for windows CI

Travis only tests on linux. We need something similar on windows (e.g. #2) . If anyone has exprience with appveyor, please come forward and add an appveyor yaml file, and I'll add it to appveyor. Otherwise this will have to wait until I figure out how to do it myself.

Fails to parse simple date string

Can someone confirm that I'm not going mad and that the latest version can't parse a simple date string on Python2.7, win64?!

In [1]: from dateutil.parser import parser, parserinfo

In [2]: p = parser()

In [3]: p.parse('01-Jan-2015')
Traceback (most recent call last):

  File "<ipython-input-3-d4aa6116cb43>", line 1, in <module>
    p.parse('01-Jan-2015')

  File "C:\dev\bin\Anaconda\lib\site-packages\dateutil\parser.py", line 387, in parse
    res = self._parse(timestr, **kwargs)

  File "C:\dev\bin\Anaconda\lib\site-packages\dateutil\parser.py", line 487, in _parse
    l = _timelex.split(timestr)         # Splits the timestr into tokens

  File "C:\dev\bin\Anaconda\lib\site-packages\dateutil\parser.py", line 174, in split
    return list(cls(s))

  File "C:\dev\bin\Anaconda\lib\site-packages\dateutil\parser.py", line 171, in next
    return self.__next__()  # Python 2.x support

  File "C:\dev\bin\Anaconda\lib\site-packages\dateutil\parser.py", line 164, in __next__
    token = self.get_token()

  File "C:\dev\bin\Anaconda\lib\site-packages\dateutil\parser.py", line 82, in get_token
    nextchar = self.instream.read(1)

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

System details:

In [6]: dateutil.__version__
Out[6]: '2.4.1'

In [7]: from IPython import sys_info

In [8]: print sys_info()
{'default_encoding': 'cp1252',
 'os_name': 'nt',
 'platform': 'Windows-7-6.1.7601-SP1',
 'sys_executable': 'C:\\dev\\bin\\Anaconda\\python.exe',
 'sys_platform': 'win32',
 'sys_version': '2.7.5 |Continuum Analytics, Inc.| (default, Jul  1 2013, 12:37:52) [MSC v.1500 64 bit (AMD64)]'}

byeaster and bysetpos can't be used together

Migrated from launchpad issue #1402868:

Quoting Thomas Roten on 2014-12-15:

I can create an rrule object like this:

>>> bysetpos = rrule(freq=0, byweekday=6, bysetpos=-13)
>>> bysetpos[0]
datetime.datetime(2015, 10, 4, 14, 18, 5)

I can also create another object like this:

>>> byeaster = rrule(freq=0, byeaster=182)
>>> byeaster[0]
datetime.datetime(2015, 10, 4, 14, 17, 56)

But, if I combine those rules, I get an exception:

>>> easter_and_setpos = rrule(freq=0, byeaster=182, byweekday=6, bysetpos=-13)
>>> easter_and_setpos[0]
Traceback (most recent call last):
  File "/Users/tsr/.virtualenvs/sacredtime/lib/python3.4/site-packages/dateutil/rrule.py", line 144, in __getitem__
    res = advance_iterator(gen)
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/Users/tsr/.virtualenvs/sacredtime/lib/python3.4/site-packages/dateutil/rrule.py", line 146, in __getitem__
     raise IndexError
 IndexError

Is this intentional or a bug?

tz.tzstr() fails on parsing timezone data file

Migrated from launchpad issue 1331576.

Quoting marcog:

With dateutil 2.2, I can't get the tzstr examples working (see below). It throws an error 'str' object has no attribute 'read'. Looking at the code, it fails on self.instream.read(1) while parsing the timezone data file. It works fine on dateutil 2.1.

In [3]: import dateutil.tz
In [4]: dateutil.tz.tzstr('EST5EDT')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-75889fcde3a9> in <module>()
----> 1 dateutil.tz.tzstr("PST")

/Library/Python/2.7/site-packages/dateutil/tz.pyc in __init__(self, s)
    579 self._s = s
    580
--> 581 res = parser._parsetz(s)
    582 if res is None:
    583 raise ValueError("unknown string format")

/Library/Python/2.7/site-packages/dateutil/parser.pyc in _parsetz(tzstr)
    923 DEFAULTTZPARSER = _tzparser()
    924 def _parsetz(tzstr):
--> 925 return DEFAULTTZPARSER.parse(tzstr)
    926
    927

/Library/Python/2.7/site-packages/dateutil/parser.pyc in parse(self, tzstr)
    770 def parse(self, tzstr):
    771 res = self._result()
--> 772 l = _timelex.split(tzstr)
    773 try:
    774

/Library/Python/2.7/site-packages/dateutil/parser.pyc in split(cls, s)
    148
    149 def split(cls, s):
--> 150 return list(cls(s))
    151 split = classmethod(split)
    152

rrulestr Generates Datetime with Incorrect Daylight Savings Value

I'm using the dateutil 2.4.2 and encountering the following error using rrulestr:

import pytz
from datetime import datetime
from dateutil.rrule import rrulestr

pacific_tz = pytz.timezone('America/Los_Angeles')
rrule_string = 'RRULE:FREQ=WEEKLY;COUNT=2;BYDAY=MO'
dt_start = pacific_tz.localize(datetime(2014, 10, 27, 9, 0))

list(rrulestr(rrule_string, dtstart=dt_start)) outputs the following:

datetime.datetime(2014, 10, 27, 9, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>), 
datetime.datetime(2014, 11, 3, 9, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)]

The second datetime is incorrect:

datetime.datetime(2014, 11, 3, 9, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>) --> November 3rd 9AM should not be in DST.

The correct datetime would be:

pytz.timezone('America/Los_Angeles').localize(datetime(2014, 11, 3, 9, 0))
datetime.datetime(2014, 11, 3, 9, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

tests missing in -2.4.1

~/cvsPortage/gentoo-x86/dev-python/python-dateutil $ l /mnt/gen2/TmpDir/portage/dev-python/python-dateutil-2.4.1/work/python-dateutil-2.4.1/dateutil

easter.py parser.py relativedelta.py rrule.py tz.py tzwin.py zoneinfo init.py

NO tests folder, no testsuite.

test_suite="dateutil.test.test"

How does one do this?????
This is from the tarball you uploaded to pypi.

Make relativedelta more inheritance friendly

Migrating this issue from launchpad issue #1010199.

Quoting Shai Berger:

Hi,

I needed to subclass relativedelta. Then, it was disappointing to find that the add, sub and neg operations explicitly return a new relativedelta object; it would be much nicer if they could return a self.class object.

Thanks,
Shai.

Adding 1 month to February 28th results in March 28th

Migrated from launchpad issue #1292043.

Quoting Florian Müller on 2014-03-13

I actually don't know, whether this is a bug but it was not the behavior I expected so I report it.

Consider the following code:

>>> datetime.date(2014,12,31) + relativedelta(months=1) + relativedelta(months=1) + relativedelta(months=1)
datetime.date(2015, 3, 28)
>>> datetime.date(2014,12,31) + relativedelta(months=3)
datetime.date(2015, 3, 31)

I really expected both examples to result in the same date.

Or want may I do to achieve the same result (other than manually check for february 28th/29th)

2.4.0 rrule produces wrong result

In [1]: import pytz

In [3]: from datetime import datetime

In [4]: from dateutil import rrule

In [5]: mlk_day = rrule.rrule(
   ...:         rrule.MONTHLY,
   ...:         bymonth=1,
   ...:         byweekday=(rrule.MO(+3)),
   ...:         cache=True,
   ...:         dtstart=datetime(1998, 1, 1, tzinfo=pytz.utc))

In [6]: mlk_day.between(datetime(2000, 1, 1, tzinfo=pytz.utc), datetime(2000, 1, 30, tzinfo=pytz.utc))
Out[6]: 
[datetime.datetime(2000, 1, 3, 0, 0, tzinfo=<UTC>),
 datetime.datetime(2000, 1, 10, 0, 0, tzinfo=<UTC>),
 datetime.datetime(2000, 1, 17, 0, 0, tzinfo=<UTC>),
 datetime.datetime(2000, 1, 24, 0, 0, tzinfo=<UTC>)]

The same code with dateutil 2.3.0 correctly produces:

In [9]: mlk_day.between(datetime(2000, 1, 1, tzinfo=pytz.utc), datetime(2000, 1, 30, tzinfo=pytz.utc)) 
Out[9]: [datetime.datetime(2000, 1, 17, 0, 0, tzinfo=<UTC>)]

Can't parse "YYYY-02".

Here is the error.

In [1]: from dateutil.parser import *

In [2]: parse('2014-02')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-f53c0530551b> in <module>()
----> 1 parse('2014-02')

/home/bluetweet/anaconda/lib/python2.7/site-packages/dateutil/parser.pyc in parse(timestr, parserinfo, **kwargs)
    980         return parser(parserinfo).parse(timestr, **kwargs)
    981     else:
--> 982         return DEFAULTPARSER.parse(timestr, **kwargs)
    983
    984

/home/bluetweet/anaconda/lib/python2.7/site-packages/dateutil/parser.pyc in parse(self, timestr, default, ignoretz, tzinfos, **kwargs)
    397                 repl[attr] = value
    398
--> 399         ret = default.replace(**repl)
    400
    401         if res.weekday is not None and not res.day:

ValueError: day is out of range for month

Empty string parses to today's date

Maybe this behavior is intended but it certainly violates the principle of least surprise.

dateutil.parser.parse('')
>>> datetime.datetime(2015, 4, 15, 0, 0)

Is this documented somewhere? I'd expect this to raise a ValueError.

Issue importing _thread in rrule.py

The following code on line 14 of rrule.py

from six.moves import _thread 

Is resulting in an import error on OS X Yosemite in Python 2.7.6. Reverting to

import thread as _thread

results in a working dateutil.

Make it possible to separate `dtstart` and `basis` in constructing `rrule` (cannot generate `rrule` backwards)

I have a case where I need to know whether or not the start date of a recurrence (given a period, an interval, and a dtstart) is far enough in the future to make the next occurrence further away than it would be if the recurrence extended back to today. (Or to simplify the problem statement, I need to take an rrule determined by an interval, a period, and a dtstart, and extend that rrule backwards in time before that dtstart).

It seems the most robust way to answer this question would be to construct an rrule whose start date is today, but which uses the real start date as the basis for determining the by* defaults. It seems to me that dateutil doesn't currently provide any public API that I could use to do this, though.

I could, of course, provide today as the original dtstart if I explicitly calculate and provide the necessary by* arguments, so that dtstart isn't used as the basis for defaulting them. But this involves duplicating a bunch of knowledge that's already encoded in rrule.__init__, which seems silly.

There would be a few possible APIs for this, but the one that seems most natural to me (and doesn't break the immutability of rrule objects, which would be problematic for caching) would be to provide a new init argument, basis, which defaults to dtstart if not provided, and is used to provide the defaults for all the by* arguments. This would allow one to separate "when does this rrule start?" from "what key datetime should be used to lock down this recurrence?"

What do you think? Is this a reasonable use case? Is there an alternative technique that I've missed? If I submitted a PR for this, would it have a shot of getting in?

I think the actual code changes would be quite simple: add the basis arg, default it to dtstart if it is None, and then replace dtstart with basis throughout __init__ wherever dtstart is currently used to determine default values for by* properties.

Break up unit tests by module

I'm thinking that, given the ever-growing number of unit tests, it seems like it might be better to split "tests.py" into "test_rrule.py", "test_parser.py", etc, to more cleanly delineate between the testing modules, and make it easier for people to add new tests with their PRs.

I can do this, but I just thought I'd open an issue first to see if there's any obvious reason why not.

2.4.1.post1 version in source

Hello,

The version of the zip file in pypy still is 2.4.1 instead of 2.4.1.post1. So buildout fails to install the egg

Thanks

Carlos

2.4.1 PyPi

Hey Guys,
please put version 2.4.1 back on pypi. At the moment there a lot of broken dependencies out there.
thx.

"Feb 2011" parsing fails but Jan, Mar-Dec works

>>> from dateutil import parser
>>> parser.parse('Jan 2011', fuzzy=True)
datetime.datetime(2011, 1, 30, 0, 0)
>>> parser.parse('Feb 2011', fuzzy=True)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/umair/dev/venvs/nathanartz/local/lib/python2.7/site-packages/dateutil/parser.py", line 743, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/home/umair/dev/venvs/nathanartz/local/lib/python2.7/site-packages/dateutil/parser.py", line 310, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month
>>> parser.parse('Dec 2011', fuzzy=True)
datetime.datetime(2011, 12, 30, 0, 0)

endless loop in rrule.py

There is a bug in rrule.py (dateutil 2.3). The while True loop on line 659 does not always terminate:

elif freq == HOURLY:
    if filtered:
        # Jump to one iteration before next day
        hour += ((23-hour)//interval)*interval
    while True:
        hour += interval
        div, mod = divmod(hour, 24)
        if div:
            hour = mod
            day += div
            fixday = True
        if not byhour or hour in byhour:
            break

Here's an example:
If the initial value of hour is an odd number, say 23, and the byhour tuple is, e.g., (0, 6, 12, 18), then we have an endless loop if interval is even because hour will always be odd and, hence, hour in byhour is never True!

Because dateutil is used by matplotlib, this causes some plotting routines to freeze.

Provide extended strftime support

In Python 2.x, strftime() is limited to years > 1900. In Python 3.3, it's limited to years > 1000. My understanding is that at least in the 2.x branch, this behavior is a WONTFIX. Is it worth it to provide an alternative version of strftime that works for older versions?

(I bring this up because I've been working on matplotlib's date-handling module and this is one of the things where it's actually doing date calculations that aren't outsourced to library calls.)

Parser UTC offset logic is inverted

my python-dateutil version: 2.4.1

i am in the time zone: CST(UTC+8)

when i use dateutil, it return different with other tools

pyhton-dateutil:

In [21]: parse("2015-03-31 00:01 UTC").astimezone(cst)
Out[21]: datetime.datetime(2015, 3, 31, 8, 1, tzinfo=tzlocal())

In [22]: parse("2015-03-31 00:01 UTC+1").astimezone(cst)
Out[22]: datetime.datetime(2015, 3, 31, 9, 1, tzinfo=tzlocal())

In [23]: parse("2015-03-31 00:01 UTC-1").astimezone(cst)
Out[23]: datetime.datetime(2015, 3, 31, 7, 1, tzinfo=tzlocal())

linux date command:

yu at debian in ~ 
(! 4076)-> date -d "2015-03-31 00:01 UTC"
Tue Mar 31 08:01:00 CST 2015
yu at debian in ~ 
(! 4076)-> date -d "2015-03-31 00:01 UTC+1"
Tue Mar 31 07:01:00 CST 2015
yu at debian in ~ 
(! 4077)-> date -d "2015-03-31 00:01 UTC-1"
Tue Mar 31 09:01:00 CST 2015

Fuzzy parsing fails when string contains 'a' without hour.

Migrating launchpad issue #1428895:

Quoting Minqi Jiang on 3/5/2015:

Fuzzy parsing fails when string contains 'a' without hour, as in

'A monkey on 10/08/1990'
'I have a meeting on March 1'

These sentences will raise a ValueError when parsed using the method

dateutil.parser.parse('your string here', fuzzy=True)

because the private _parse method in parse.py raises a ValueError if 'a' is detected (for AM) without a corresponding hour. This is not an issue in python-dateutil versions < 2.4.

Issue when parsing ISO8601 date string on GAE

I'm using version 2.4.1 in both a local GAE environment as well as in a local ipython instance.
In both I attempt to parse the string using:

asdf = dateutil.parser.parse(u'2014-06-01T00:00:00.000Z')
print asdf.tzinfo

On the local machine, this properly shows tzutc as the result
When using the GAE environment, this instead returns a datetime with tzlocal

It looks like this is being set in parser.py at line 424 (425 after my pdb insertion)

(Pdb) l
420                         raise ValueError("Offset must be tzinfo subclass, "
421                                          "tz string, or int offset.")
422                     ret = ret.replace(tzinfo=tzinfo)
423                 elif res.tzname and res.tzname in time.tzname:
424                     import pdb; pdb.set_trace()
425  ->                 ret = ret.replace(tzinfo=tz.tzlocal())

I'm not sure what the issue is but this seems very strange.

COMPAT: dateutil 2.2/2.3 on linux 3.17

as mentioned in several issues for pandas.
seems that a very recent release of linux kernel has broken dateutil both 2.2. and 2.3

these are showing up in various tests in pandas. essentially the tz files cannot be found.
I don't think this is a pandas bug as we tests compat for 2.2/2.3 on all platforms ok, though
using kernel 2.6 on linux (on travis CI)

2.3
pandas-dev/pandas#9059
OS: Linux
OS-release: 3.17-1-amd64

2.2 & 2.3
pandas-dev/pandas#8639
OS: Linux
OS-release: 3.17.4-lh-nvidia

rrule issue: 3rd thursday in month

When I run the following code in dateutil 1.5, I get a different answer to dateutil 2.4:

In [1]: from dateutil.rrule import rrule, MONTHLY, TH
In [2]: from datetime import date, datetime
In [3]: r=rrule(MONTHLY, byweekday=TH(3), bymonth=(3,6,9,12), dtstart=datetime(2009,3,19))
In [4]: r.after(datetime(2015,3,1,12))

dateutil 1.5 gives: datetime.datetime(2015, 3, 19, 0, 0)
dateutil 2.4 gives: datetime.datetime(2015, 3, 5, 0, 0)

datetime(2015,3,5) is not the 3rd Thursday in March. datetime(2015,3,19) IS the third thursday. Any ideas what is going on?

setup.py should require six at least version 1.5

after installation with python setup.py install , in python 2.7, tests failed to run with message related to _thread

dateutil.rrule does
from six.moves import _thread

but six version needs to be at least 1.5 for that

Defect seen in dateutil v2.3 and master b2615c7 from Tue Dec 9 21:42:17 2014 +0200

EDIT: I was at six vs 1.2 before, updated to latest in pypi, vs 1.8 ATM.
I don't tested versions in ´´´1.5 <= vs < 1.8´´´ so it is possible that other features need a higher version than 1.5; 1.5 is the minimal to solve the _thread traceback.

Unable to build msi

Using python setup.py bdist_msi:

...
running install_scripts
creating dist
Traceback (most recent call last):
  File "setup.py", line 50, in <module>
    test_suite="dateutil.test.test"
  File "C:\Python27\lib\distutils\core.py", line 151, in setup
    dist.run_commands()
  File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "C:\Python27\lib\distutils\command\bdist_msi.py", line 247, in run
    sversion, author)
  File "C:\Python27\lib\msilib\__init__.py", line 148, in init_database
    si.SetProperty(PID_SUBJECT, ProductName)
TypeError: unsupported type

Provide version of Olson's database as a constant

The documentation claims that:

Internal up-to-date world timezone information based on Olson's database.

However, the current used version of the database cannot be found from installed package. Please provide constant with stored version of used database.

Relativedelta constructed from fractions of hours... (Feature request)

I would like to request feature to allow relativedelta construction from e.g. hour fractions.
In some business applications I met the practice to store total hours count represented as float. In one even as total days count (represented by float). Now I need to integrate with them.
thx

Garbage input for parse returns a datetime, not an TypeError

A user reported a bug:

When "a" is provided as input str to the parser, TypeError exception is
expected. Instead, the parser returns a datetime object.

>>> import dateutil.parser as d_parser
>>> d_parser.parse*('a')*
datetime.datetime(2014, 11, 10, 0, 0)

tzname assumes there is a good name?

from dateutil.parser import parse
dt = parse('2010-07-15T17:58:00-07:00')
dt.tzname()

and I get this exception:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dt.tzname()
  File "/home/sontek/venvs/monkeylib/src/MonkeyLib/.tox/py27/local/lib/python2.7/site-packages/dateutil/tz.py", line 41, in inner_func
    return myfunc(*args, **kwargs).encode()
AttributeError: 'NoneType' object has no attribute 'encode'

Parsing with too big year

When parsing a string for which the year part will be a too much big integer, an OverFlowError is raised:

Traceback (most recent call last):
  File "tryton/common/datetime_.py", line 151, in focus_out
    self.parse()
  File "tryton/common/datetime_.py", line 87, in parse
    date = date_parse(text, self.__format).date()
  File "tryton/common/datetime_.py", line 26, in date_parse
    return parse(text, dayfirst=dayfirst, yearfirst=yearfirst, ignoretz=True)
  File "/home/ced/.local/lib/python2.7/site-packages/dateutil/parser.py", line 697, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/home/ced/.local/lib/python2.7/site-packages/dateutil/parser.py", line 310, in parse
    ret = default.replace(**repl)
OverflowError: Python int too large to convert to C long

I think the error should be catch and raised as a ValueError.

Spaces are not treaded well

Is it expected behavior?

>>> from dateutil import parser
>>> parser.parse("Jan.5.2014")
datetime.datetime(2014, 1, 5, 0, 0)
>>> parser.parse("Jan. 5.2014")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/allactaga/Development/Environments/test/lib/python2.7/site-packages/dateutil/parser.py", line 743, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/allactaga/Development/Environments/test/lib/python2.7/site-packages/dateutil/parser.py", line 303, in parse
    raise ValueError("unknown string format")
ValueError: unknown string format

Add ability to get Olson/POSIX name of a timezone

I want to save a timezone name in the database, so maybe it would be nice to have an ability to get Olson or POSIX name of the timezone.
Example:

>>> from dateutil import tz
>>> tzla = tz.gettz('America/Los_Angeles')
>>> print tzla.name
America/Los_Angeles
>>> tzla = tz.gettz('America/Los Angeles')
>>> print tzla.name
America/Los_Angeles
>>> tzmet = tz.gettz('MET')
>>> print tzla.name
MET

Please let me know what you think? I can try to implement this.

develop rrule2

I have a big project in mind that I call rrule2. The idea is to be much more pythonic, and to iterate over the recurrences using itertools.product of byyear, bymonth.....
So the idea is as follows:

  1. Convert the frequency and interval data to an iterator. i.e. having frequency=HOURLY should not be much different than byhour=tuple(range(24)), except for the handling of missing inputs and dtstart.
  2. Convert missing inputs to iterators
  3. Iterate over the product of all by__ tuples, carefully skipping impossible dates.

I am not sure if the idea is feasable at all. rrule is a very compilcated beast. But I'd like to try.

Implementation

  1. Create a new rrule2 class, with several user warnings that nothing is working/finite, and that rrule2 will be merged into rrule
  2. Develop and test (using the rrule test suite)
  3. When the API gets mature, consider replacing rrule with rrule2.

Error when creating datetime.time with dateutil.tz.tzlocal

Migrating launchpad bug #1256908.

Quoting Jan Spurny on 2013-12-02:

Creating datetime.time with dateutil.tz.tzlocal creates valid datetime.time object, but this object raises error when __str__, __repr__ or isoformat method is called on it.

Demonstration:

 >>> import datetime
 >>> import dateutil.tz
 >>> t1 = datetime.time(1, 2, tzinfo=dateutil.tz.tzutc())
 >>> t2 = datetime.time(1, 2, tzinfo=dateutil.tz.tzlocal())
 >>> t1
 datetime.time(1, 2, tzinfo=tzutc())
 >>> t2
 datetime.time(1, 2, tzinfo=tzlocal())
 >>> print t1
 01:02:00+00:00
 >>> print t2
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/lib/pymodules/python2.6/dateutil/tz.py", line 92, in utcoffset
     if self._isdst(dt):
   File "/usr/lib/pymodules/python2.6/dateutil/tz.py", line 134, in _isdst
     + dt.second)
 AttributeError: 'NoneType' object has no attribute 'toordinal'

My locale timezone is "Europe/Prague", python2.6, dateutil 1.4.1, debian linux.

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.