python_dateutil-4.0.0/CONTRIBUTING.md0000644000000000000000000001634213615410400014106 0ustar00# Contributing This document outlines the ways to contribute to `python-dateutil`. This is a fairly small, low-traffic project, so most of the contribution norms (coding style, acceptance criteria) have been developed ad hoc and this document will not be exhaustive. If you are interested in contributing code or documentation, please take a moment to at least review the license section to understand how your code will be licensed. ## Types of contribution ### Bug reports Bug reports are an important type of contribution - it's important to get feedback about how the library is failing, and there's no better way to do that than to hear about real-life failure cases. A good bug report will include: 1. A minimal, reproducible example - a small, self-contained script that can reproduce the behavior is the best way to get your bug fixed. For more information and tips on how to structure these, read [Stack Overflow's guide to creating a minimal, complete, verified example](https://stackoverflow.com/help/mcve). 2. The platform and versions of everything involved, at a minimum please include operating system, `python` version and `dateutil` version. Instructions on getting your versions: - `dateutil`: `python -c "import dateutil; print(dateutil.__version__)"` - `Python`: `python --version` 3. A description of the problem - what *is* happening and what *should* happen. While pull requests fixing bugs are accepted, they are *not* required - the bug report in itself is a great contribution. ### Feature requests If you would like to see a new feature in `dateutil`, it is probably best to start an issue for discussion rather than taking the time to implement a feature which may or may not be appropriate for `dateutil`'s API. For minor features (ones where you don't have to put a lot of effort into the PR), a pull request is fine but still not necessary. ### Pull requests If you would like to fix something in `dateutil` - improvements to documentation, bug fixes, feature implementations, fixes to the build system, etc - pull requests are welcome! Where possible, try to keep your coding to [PEP 8 style](https://www.python.org/dev/peps/pep-0008/), with the minor modification that the existing `dateutil` class naming style does not use the CapWords convention, or where the existing style does not follow PEP 8. The most important thing to include in your pull request are *tests* - please write one or more tests to cover the behavior you intend your patch to improve. Ideally, tests would use only the public interface - try to get 100% difference coverage using only supported behavior of the API. #### Changelog To keep users abreast of the changes to the module and to give proper credit, `dateutil` maintains a changelog, which is managed by [towncrier](https://github.com/hawkowl/towncrier). To add a changelog entry, make a new file called `..rst` in the `changelog.d` directory, where `` is the number of the PR you've just made (it's easiest to add the changelog *after* you've created the PR so you'll have this number), and `` is one of the following types: - `feature`: A new feature, (e.g. a new function, method, attribute, etc) - `bugfix`: A fix to a bug - `doc`: A change to the documentation - `deprecations`: Used if deprecating a feature or dropping support for a Python version. - `data`: An update to the bundled time zone data. - `misc`: A change that has no interesting effect for end users, such as fixes to the test suite or CI. PRs that include a feature or bugfix *and* a deprecation should create a separate entry for the deprecation. > {description of changes}. Reported by @{reporter} (gh issue #{issue\_no}). Fixed by @{patch submitter} (gh pr #{pr\_no}) An example changelog entry might be: **581.bugfix.rst** ``` Fixed issue where the tz.tzstr constructor would erroneously succeed if passed an invalid value for tzstr. Reported by @pganssle (gh issue #259). Fixed by @pablogsal (gh pr #581) ``` For bugs reported and fixed by the same person use "Reported and fixed by @{patch submitter}". It is not necessary to create a GitHub issue just for the purpose of mentioning it in the changelog, if the PR *is* the report, mentioning the PR is enough. ## License Starting December 1, 2017, all contributions will be assumed to be released under a dual license - the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0) and the [3-Clause BSD License](https://opensource.org/licenses/BSD-3-Clause) unless otherwise specified in the pull request. All contributions before December 1, 2017 except those explicitly relicensed, are only under the 3-clause BSD license. ## Development Setup ### Using a virtual environment It is advisable to work in a virtual environment for development of `dateutil`. This can be done using [virtualenv](https://virtualenv.pypa.io): ```bash python -m virtualenv .venv # Create virtual environment in .venv directory source .venv/bin/activate # Activate the virtual environment ``` Alternatively you can create a [conda environment](https://conda.io/docs/user-guide/tasks/manage-environments.html): ```bash conda create -n dateutil # Create a conda environment # conda create -n dateutil python=3.6 # Or specify a version source activate dateutil # Activate the conda environment ``` Once your virtual environment is created, install the library in development mode: ```bash pip install -e . ``` This will allow scripts run in your virtual environment to use the version of `dateutil` in your local directory. If you also want to run the tests in your local directory, install the test dependencies: ```bash pip install -r requirements-dev.txt ``` ## Testing The best way to test `dateutil` is to run `tox`. By default, `tox` will test against all supported versions of Python installed on your system. To limit the number of tests, run a specific subset of environments. For example, to run only on Python 3.11 and Python 3.13: ```bash tox -e py311,py313 ``` For faster environment creation and dependency installation, you can install `tox` with the `tox-uv` plugin using [uv](https://docs.astral.sh/uv/): ```bash uv tool install tox --with tox-uv ``` The same `tox` commands work with either the uv plugin or the default installer. You can also pass arguments to `pytest` through `tox` by placing them after `--`: ```bash tox -e py311 -- -m tzstr ``` This will pass the `-m tzstr` parameter to `pytest`, running only the tests with the `tzstr` mark. `tox` runs the tests in parallel with [pytest-xdist](https://pytest-xdist.readthedocs.io/). To run them in a single process, for example to use `--pdb`, pass `-n 0`: ```bash tox -e py311 -- -n 0 --pdb ``` The tests can also be run directly by running `pytest` or `python -m pytest` in the root directory. This will be likely be less thorough but is often faster and is a good first pass to check your changes. The GitHub Actions workflows are checked with [zizmor](https://docs.zizmor.sh/). To run the audit locally: ```bash uvx zizmor .github/workflows ``` This uses the latest zizmor release, which may report different findings from the version bundled with the pinned zizmor action in CI. All GitHub pull requests are automatically tested using [GitHub Actions](https://github.com/dateutil/dateutil/actions/). python_dateutil-4.0.0/NEWS0000644000000000000000000014717513615410400012365 0ustar00Version 4.0.0 (2026-11-01) ========================== ``dateutil`` 4.0 requires Python 3.11 or later and no longer depends on ``six``. Apart from that, the changes in this release are bug fixes, but note that ``isoparse`` is now stricter about the numeric fields it accepts (see below). Deprecations ------------ - Dropped support for Python versions older than 3.11 and removed the dependency on ``six``, along with Python 2 compatibility helpers that were never part of the public API, such as ``dateutil.tz.tzname_in_python2``. (gh pr #1625) Bugfixes -------- - ``parser.isoparse``, and the ``isoparser`` methods ``parse_isodate``, ``parse_isotime`` and ``parse_tzstr``, now require each numeric field to be exactly the expected number of ASCII digits. Strings that were previously accepted, such as ``20200728121240`` (read as 21:24), ``2014- 4-21`` and ``2_14-04-21``, and offsets such as ``+-1:00``, now raise ``ValueError``. ``tzical`` applies the same check to ``TZOFFSETFROM`` and ``TZOFFSETTO``. Reported by @janos-gonye (gh issue #1074). Fixed by @varun3257 (gh pr #1617). - Fixed an issue where iterating over a cached ``rrule`` or ``rruleset`` could hang forever if another iterator over the same rule had already completed the cache, for example when a cached ``rrule`` was included twice in an ``rruleset``. Reported by @bysiber (gh pr #1455). Fixed by @pganssle (gh pr #1655). - Unpickling a ``tzutc`` now gives the ``dateutil.tz.UTC`` singleton, and unpickling a ``tzoffset`` gives the same object as calling ``tzoffset(name, offset)``. Previously unpickling bypassed the singleton-generation logic. Reported and fixed by @masipcat (gh issue #1051, gh pr #1053). - ``relativedelta(yearday=366)`` now resolves to December 31 in leap years. Previously it gave December 30, the same date as ``yearday=365``. Reported and fixed by @Master-Norna (gh pr #1583). Misc ---- - The build backend is now Hatchling, and the package metadata is in ``pyproject.toml``. Versions are still derived from Git tags and exposed as ``dateutil.__version__``. This mainly affects people building ``dateutil`` from source. (gh pr #1637, #1638) - Changes to CI, tests and release tooling that do not affect users of the package: gh pr #1636, #1644, #1645, #1646, #1648, #1649, #1650. Version 3.0.0 (2026-10-21) ========================== **This is the last major version of** ``dateutil`` **that will support any version of Python older than 3.11.** The next release will be the 4.x series, which will support Python 3.11 and later. We may release fixes for serious bugs in the 3.0.x series, but there are no plans for new features there. The biggest change in this release is a rewrite of ``tz.tzfile``, which affects nearly every user of ``dateutil.tz`` and changes the UTC offset of nonexistent times (see below). ``dateutil`` also now depends on the ``tzdata`` package, and no longer ships its own time zone database. Data updates ------------ - ``dateutil`` no longer bundles a copy of the IANA time zone database. Time zone data now comes from the system (see ``dateutil.tz.TZPATH``) or, failing that, from the new ``tzdata`` dependency, so the data version is whatever version of ``tzdata`` is installed. (gh pr #1130) Features -------- - Rewrote ``tz.tzfile`` based on a backport of the ``zoneinfo`` module's pure-Python implementation. This adds support for Version 2 and Version 3 ``tzfile(5)`` binaries, resolving issues with timestamps beyond 2038 and "slim" format binaries. (gh issues #462, #1059, gh pr #1130) - Added ``dateutil.tz.TZPATH`` and ``dateutil.tz.reset_tzpath`` to allow for runtime configuration of the IANA time zone data search path. These replace the mutable ``dateutil.tz.TZPATHS`` list, which has been removed. (gh pr #1130) - ``dateutil`` now depends on the ``tzdata`` package, which ``gettz`` consults after the search path and before the Windows registry. On Windows this means that names that are both IANA keys and Windows time zone names, such as ``"UTC"``, now return a ``tzfile`` rather than a ``tzwin``. (gh pr #1130) Bugfixes -------- - ``tz.tzfile`` now follows PEP 495 for times that fall in a gap: with ``fold=0`` it uses the offset from before the transition, and with ``fold=1`` the offset from after it. Previously it always used the offset from after the transition, so for example ``datetime(2003, 4, 6, 2, 30, tzinfo=tz.gettz("America/New_York"))`` had a UTC offset of -04:00, where it now has -05:00, the same as with ``zoneinfo``. (gh pr #1130) - ``tz.tzfile`` objects for fixed-offset zones, such as ``tz.gettz("UTC")``, now return their offset, DST offset and abbreviation when ``utcoffset``, ``dst`` and ``tzname`` are called with ``None``, as ``tz.tzutc``, ``tz.tzoffset`` and ``zoneinfo.ZoneInfo`` do. This means that ``datetime.time`` objects with such a zone attached are now aware: ``time(12, tzinfo=tz.gettz("UTC")).isoformat()`` is now ``"12:00:00+00:00"`` rather than ``"12:00:00"``. (gh pr #1130) - ``tz.tzfile`` now infers ``dst()`` from the standard time on both sides of each DST period, rather than only the one before it, and does so for each transition rather than for each local time type. This fixes ``dst()`` for double summer time (e.g. in ``Europe/London`` in the 1940s), for half-hour DST (e.g. in ``Pacific/Rarotonga``) and where the standard offset changed at the same time as a DST transition (e.g. in ``America/Bahia_Banderas`` in 2010). Against the standard offsets in the tz database source, the only remaining errors are in ``Europe/Paris`` in 1944 and 1945. (gh pr #1130) - Fixed ``rrulestr`` raising ``ValueError`` on experimental ``X-`` parameters in an ``RRULE`` line (such as GNOME Evolution's ``X-EVOLUTION-ENDDATE``); these are now ignored as RFC 5545 permits. Fixed by @yajo (gh pr #1374) - Enabled pickling and deepcopy of cached ``rrule`` and ``rruleset`` instances. The cache setting is preserved, and cached results are regenerated on demand without copying locks or generators. Reported by @niccokunzmann (gh issue #1369). Fixed by @Jay1023CN (gh pr #1600). - Fixed ``relativedelta.__ne__`` raising ``TypeError`` when comparing against an unsupported type such as ``None``; it now returns ``True``. Reported and fixed by @kevinkt1 (gh issue #1157, gh pr #1158) - Raised the minimum version of ``six`` to 1.6, fixing ``No module named 'six.moves'`` errors with older versions. Reported by @skytreader (gh issue #1415), fixed by @jdarias3 (gh pr #1424). Deprecations ------------ - Deprecated the ``dateutil.zoneinfo`` module. The module now acts as a wrapper around the ``tzdata`` package and will be removed in a future version. Users are encouraged to migrate to ``dateutil.tz.gettz`` or the standard library's ``zoneinfo`` module. ``dateutil.zoneinfo.rebuild.rebuild`` no longer does anything, and by default raises ``RebuildDeprecationWarning`` as an error; filter the warning to call it as a no-op. (gh pr #1130) - Deprecated passing ``gettz`` a relative key that refers to a file outside of every directory on ``TZPATH``, such as ``"../../etc/localtime"``. By default this now raises ``dateutil.tz.DeprecatedTzKeyWarning`` as an error; filter the warning to keep the old behavior for now, or pass an absolute path instead. (gh pr #1130) Documentation changes --------------------- - Added intersphinx to the docs build and cleaned up some broken links. (gh pr #1463) Misc ---- - Releases are now uploaded to PyPI using trusted publishing, and the built sdist and wheel are tested on all supported platforms before upload. (gh pr #1619, #1622) - Changes to CI, tests and release tooling that do not affect users of the package: gh pr #1417, #1462, #1464, #1465, #1466, #1467, #1468, #1469, #1470, #1499, #1501, #1504, #1576, #1577, #1578, #1581, #1585. Version 2.9.0.post0 (2024-03-01) ================================ Bugfixes -------- - Pinned ``setuptools_scm`` to ``<8``, which should make the generated ``_version.py`` file compatible with all supported versions of Python. Version 2.9.0 (2024-02-29) ========================== Data updates ------------ - Updated tzdata version to 2024a. (gh pr #1342) Features -------- - Made all ``dateutil`` submodules lazily imported using `PEP 562 `_. On Python 3.7+, things like ``import dateutil; dateutil.tz.gettz("America/New_York")`` will now work without explicitly importing ``dateutil.tz``, with the import occurring behind the scenes on first use. The old behavior remains on Python 3.6 and earlier. Fixed by Orson Adams. (gh issue #771, gh pr #1007) Bugfixes -------- - Removed a call to ``datetime.utcfromtimestamp``, which is deprecated as of Python 3.12. Reported by Hugo van Kemenade (gh pr #1284), fixed by Thomas Grainger (gh pr #1285). Documentation changes --------------------- - Added note into docs and tests where relativedelta would return last day of the month only if the same day on a different month resolves to a date that doesn't exist. Reported by @hawkEye-01 (gh issue #1167). Fixed by @Mifrill (gh pr #1168) Version 2.8.2 (2021-07-08) ========================== Data updates ------------ - Updated tzdata version to 2021a. (gh pr #1128) Bugfixes -------- - Fixed a bug in the parser where non-``ValueError`` exceptions would be raised during exception handling; this would happen, for example, if an ``IllegalMonthError`` was raised in ``dateutil`` code. Fixed by Mark Bailey. (gh issue #981, pr #987). - Fixed the custom ``repr`` for ``dateutil.parser.ParserError``, which was not defined due to an indentation error. (gh issue #991, gh pr #993) - Fixed a bug that caused ``b'`` prefixes to appear in parse_isodate exception messages. Reported and fixed by Paul Brown (@pawl) (gh pr #1122) - Make ``isoparse`` raise when trying to parse times with inconsistent use of `:` separator. Reported and fixed by @mariocj89 (gh pr #1125). - Fixed ``tz.gettz()`` not returning local time when passed an empty string. Reported by @labrys (gh issues #925, #926). Fixed by @ffe4 (gh pr #1024) Documentation changes --------------------- - Rearranged parser documentation into "Functions", "Classes" and "Warnings and Exceptions" categories. (gh issue #992, pr #994). - Updated ``parser.parse`` documentation to reflect the switch from ``ValueError`` to ``ParserError``. (gh issue #992, pr #994). - Fixed methods in the ``rrule`` module not being displayed in the docs. (gh pr #1025) - Changed some relative links in the exercise documentation to refer to the document locations in the input tree, rather than the generated HTML files in the HTML output tree (which presumably will not exist in non-HTML output formats). (gh pr #1078). Misc ---- - Moved ``test_imports.py``, ``test_internals.py`` and ``test_utils.py`` to pytest. Reported and fixed by @jpurviance (gh pr #978) - Added project_urls for documentation and source. Patch by @andriyor (gh pr #975). - Simplified handling of bytes and bytearray in ``_parser._timelex``. Reported and fixed by @frenzymadness (gh issue #1060). - Changed the tests against the upstream tz database to always generate fat binaries, since until GH-590 and GH-1059 are resolved, "slim" zic binaries will cause problems in many zones, causing the tests to fail. This also updates ``zoneinfo.rebuild`` to always generate fat binaries. (gh pr #1076). - Moved sdist and wheel generation to use `python-build`. Reported and fixed by @mariocj89 (gh pr #1133). Version 2.8.1 (2019-11-03) ========================== Data updates ------------ - Updated tzdata version to 2019c. Bugfixes -------- - Fixed a race condition in the ``tzoffset`` and ``tzstr`` "strong" caches on Python 2.7. Reported by @kainjow (gh issue #901). - Parsing errors will now raise ``ParserError``, a subclass of ``ValueError``, which has a nicer string representation. Patch by @gfyoung (gh pr #881). - ``parser.parse`` will now raise ``TypeError`` when ``tzinfos`` is passed a type that cannot be interpreted as a time zone. Prior to this change, it would raise an ``UnboundLocalError`` instead. Patch by @jbrockmendel (gh pr #891). - Changed error message raised when when passing a ``bytes`` object as the time zone name to gettz in Python 3. Reported and fixed by @labrys () (gh issue #927, gh pr #935). - Changed compatibility logic to support a potential Python 4.0 release. Patch by Hugo van Kemenade (gh pr #950). - Updated many modules to use ``tz.UTC`` in favor of ``tz.tzutc()`` internally, to avoid an unnecessary function call. (gh pr #910). - Fixed issue where ``dateutil.tz`` was using a backported version of ``contextlib.nullcontext`` even in Python 3.7 due to a malformed import statement. (gh pr #963). Tests ----- - Switched from using assertWarns to using pytest.warns in the test suite. (gh pr #969). - Fix typo in setup.cfg causing PendingDeprecationWarning to not be explicitly specified as an error in the warnings filter. (gh pr #966) - Fixed issue where ``test_tzlocal_offset_equal`` would fail in certain environments (such as FreeBSD) due to an invalid assumption about what time zone names are provided. Reported and fixed by Kubilay Kocak (gh issue #918, pr #928). - Fixed a minor bug in ``test_isoparser`` related to ``bytes``/``str`` handling. Fixed by @fhuang5 (gh issue #776, gh pr #879). - Explicitly listed all markers used in the pytest configuration. (gh pr #915) - Extensive improvements to the parser test suite, including the adoption of ``pytest``-style tests and the addition of parametrization of several test cases. Patches by @jbrockmendel (gh prs #735, #890, #892, #894). - Added tests for tzinfos input types. Patch by @jbrockmendel (gh pr #891). - Fixed failure of test suite when changing the TZ variable is forbidden. Patch by @shadchin (gh pr #893). - Pinned all test dependencies on Python 3.3. (gh prs #934, #962) Documentation changes --------------------- - Fixed many misspellings, typos and styling errors in the comments and documentation. Patch by Hugo van Kemenade (gh pr #952). Misc ---- - Added Python 3.8 to the trove classifiers. (gh pr #970) - Moved as many keys from ``setup.py`` to ``setup.cfg`` as possible. Fixed by @FakeNameSE, @aquinlan82, @jachen20, and @gurgenz221 (gh issue #871, gh pr #880). - Reorganized ``parser`` methods by functionality. Patch by @jbrockmendel (gh pr #882). - Switched ``release.py`` over to using ``pep517.build`` for creating releases, rather than direct invocations of ``setup.py``. Fixed by @smeng10 (gh issue #869, gh pr #875). - Added a "build" environment into the tox configuration, to handle dependency management when making releases. Fixed by @smeng10 (gh issue #870,r gh pr #876). - GH #916, GH #971 Version 2.8.0 (2019-02-04) ========================== Data updates ------------ - Updated tzdata version to to 2018i. Features -------- - Added support for ``EXDATE`` parameters when parsing ``rrule`` strings. Reported by @mlorant (gh issue #410), fixed by @nicoe (gh pr #859). - Added support for sub-minute time zone offsets in Python 3.6+. Fixed by @cssherry (gh issue #582, pr #763) - Switched the ``tzoffset``, ``tzstr`` and ``gettz`` caches over to using weak references, so that the cache expires when no other references to the original ``tzinfo`` objects exist. This cache-expiry behavior is not guaranteed in the public interface and may change in the future. To improve performance in the case where transient references to the same time zones are repeatedly created but no strong reference is continuously held, a smaller "strong value" cache was also added. Weak value cache implemented by @cs-cordero (gh pr #672, #801), strong cache added by Gökçen Nurlu (gh issue #691, gh pr #761) Bugfixes -------- - Add support for ISO 8601 times with comma as the decimal separator in the ``dateutil.parser.isoparse`` function. (gh pr #721) - Changed handling of ``T24:00`` to be compliant with the standard. ``T24:00`` now represents midnight on the *following* day. Fixed by @cheukting (gh issue #658, gh pr #751) - Fixed an issue where ``isoparser.parse_isotime`` was unable to handle the ``24:00`` variant representation of midnight. (gh pr #773) - Added support for more than 6 fractional digits in `isoparse`. Reported and fixed by @jayschwa (gh issue #786, gh pr #787). - Added 'z' (lower case Z) as valid UTC time zone in isoparser. Reported by @cjgibson (gh issue #820). Fixed by @Cheukting (gh pr #822) - Fixed a bug with base offset changes during DST in ``tzfile``, and refactored the way base offset changes are detected. Originally reported on Stack Overflow by @MartinThoma. (gh issue #812, gh pr #810) - Fixed error condition in ``tz.gettz`` when a non-ASCII timezone is passed on Windows in Python 2.7. (gh issue #802, pr #861) - Improved performance and inspection properties of ``tzname`` methods. (gh pr #811) - Removed unnecessary binary_type compatibility shims. Added by @jdufresne (gh pr #817) - Changed ``python setup.py test`` to print an error to ``stderr`` and exit with 1 instead of 0. Reported and fixed by @hroncok (gh pr #814) - Added a ``pyproject.toml`` file with build requirements and an explicitly specified build backend. (gh issue #736, gh prs #746, #863) Documentation changes --------------------- - Added documentation for the ``rrule.rrulestr`` function. Fixed by @prdickson (gh issue #623, gh pr #762) - Add documentation for the ``dateutil.tz.win`` module and mocked out certain Windows-specific modules so that autodoc can still be run on non-Windows systems. (gh issue #442, pr #715) - Added changelog to documentation. (gh issue #692, gh pr #707) - Improved documentation on the use of ``until`` and ``count`` parameters in ``rrule``. Fixed by @lucaferocino (gh pr #755). - Added an example of how to use a custom ``parserinfo`` subclass to parse non-standard datetime formats in the examples documentation for ``parser``. Added by @prdickson (gh #753) - Expanded the description and examples in the ``relativedelta`` class. Contributed by @andrewcbennett (gh pr #759) - Improved the contributing documentation to clarify where to put new changelog files. Contributed by @andrewcbennett (gh pr #757) - Fixed a broken doctest in the ``relativedelta`` module. Fixed by @nherriot (gh pr #758). - Reorganized ``dateutil.tz`` documentation and fixed issue with the ``dateutil.tz`` docstring. (gh pr #714) Misc ---- - GH #720, GH #723, GH #726, GH #727, GH #740, GH #750, GH #760, GH #767, GH #772, GH #773, GH #780, GH #784, GH #785, GH #791, GH #799, GH #813, GH #836, GH #839, GH #857 Version 2.7.5 (2018-10-27) ========================== Data updates ------------ - Update tzdata to 2018g Version 2.7.4 (2018-10-24) ========================== Data updates ------------ - Updated tzdata version to 2018f. Version 2.7.3 (2018-05-09) ========================== Data updates ------------ - Update tzdata to 2018e. (gh pr #710) Bugfixes -------- - Fixed an issue where ``parser.parse`` would raise ``Decimal``-specific errors instead of a standard ``ValueError`` if certain malformed values were parsed (e.g. ``NaN`` or infinite values). Reported and fixed by @amureki (gh issue #662, gh pr #679). - Fixed issue in ``parser`` where a ``tzinfos`` call explicitly returning ``None`` would throw a ``ValueError``. Fixed by @parsethis (gh issue #661, gh pr #681) - Fixed incorrect parsing of certain dates earlier than 100 AD when represented in the form "%B.%Y.%d", e.g. "December.0031.30". (gh issue #687, pr #700) - Added time zone inference when initializing an ``rrule`` with a specified ``UNTIL`` but without an explicitly specified ``DTSTART``; the time zone of the generated ``DTSTART`` will now be taken from the ``UNTIL`` rule. Reported by @href (gh issue #652). Fixed by @absreim (gh pr #693). Documentation changes --------------------- - Corrected link syntax and updated URL to https for ISO year week number notation in relativedelta examples. (gh issue #670, pr #711) - Add doctest examples to tzfile documentation. Done by @weatherpattern and @pganssle (gh pr #671) - Updated the documentation for relativedelta. Removed references to tuple arguments for weekday, explained effect of weekday(_, 1) and better explained the order of operations that relativedelta applies. Fixed by @kvn219 @huangy22 and @ElliotJH (gh pr #673) - Added changelog to documentation. (gh issue #692, gh pr #707) - Changed order of keywords in rrule docstring. Reported and fixed by @rmahajan14 (gh issue #686, gh pr #695). - Added documentation for ``dateutil.tz.gettz``. Reported by @pganssle (gh issue #647). Fixed by @weatherpattern (gh pr #704) - Cleaned up malformed RST in the ``tz`` documentation. (gh issue #702, gh pr #706) - Changed the default theme to ``sphinx_rtd_theme``, and changed the sphinx configuration accordingly. (gh pr #707) - Reorganized ``dateutil.tz`` documentation and fixed issue with the ``dateutil.tz`` docstring. (gh pr #714) Misc ---- - GH #674, GH #688, GH #699 Version 2.7.2 (2018-03-26) ========================== Bugfixes -------- - Fixed an issue with the setup script running in non-UTF-8 environment. Reported and fixed by @gergondet (gh pr #651) Misc ---- - GH #655 Version 2.7.1 (2018-03-24) =========================== Data updates ------------ - Updated tzdata version to 2018d. Bugfixes -------- - Fixed issue where parser.parse would occasionally raise decimal.Decimal-specific error types rather than ValueError. Reported by @amureki (gh issue #632). Fixed by @pganssle (gh pr #636). - Improve error message when rrule's dtstart and until are not both naive or both aware. Reported and fixed by @ryanpetrello (gh issue #633, gh pr #634) Misc ---- - GH #644, GH #648 Version 2.7.0 ============= - Dropped support for Python 2.6 (gh pr #362 by @jdufresne) - Dropped support for Python 3.2 (gh pr #626) - Updated zoneinfo file to 2018c (gh pr #616) - Changed licensing scheme so all new contributions are dual licensed under Apache 2.0 and BSD. (gh pr #542, issue #496) - Added __all__ variable to the root package. Reported by @tebriel (gh issue #406), fixed by @mariocj89 (gh pr #494) - Added python_requires to setup.py so that pip will distribute the right version of dateutil. Fixed by @jakec-github (gh issue #537, pr #552) - Added the utils submodule, for miscellaneous utilities. - Added within_delta function to utils - added by @justanr (gh issue #432, gh pr #437) - Added today function to utils (gh pr #474) - Added default_tzinfo function to utils (gh pr #475), solving an issue reported by @nealmcb (gh issue #94) - Added dedicated ISO 8601 parsing function isoparse (gh issue #424). Initial implementation by @pganssle in gh pr #489 and #622, with a pre-release fix by @kirit93 (gh issue #546, gh pr #573). - Moved parser module into parser/_parser.py and officially deprecated the use of several private functions and classes from that module. (gh pr #501, #515) - Tweaked parser error message to include rejected string format, added by @pbiering (gh pr #300) - Add support for parsing bytesarray, reported by @uckelman (gh issue #417) and fixed by @uckelman and @pganssle (gh pr #514) - Started raising a warning when the parser finds a timezone string that it cannot construct a tzinfo instance for (rather than succeeding with no indication of an error). Reported and fixed by @jbrockmendel (gh pr #540) - Dropped the use of assert in the parser. Fixed by @jbrockmendel (gh pr #502) - Fixed to assertion logic in parser to support dates like '2015-15-May', reported and fixed by @jbrockmendel (gh pr #409) - Fixed IndexError in parser on dates with trailing colons, reported and fixed by @jbrockmendel (gh pr #420) - Fixed bug where hours were not validated, leading to improper parse. Reported by @heappro (gh pr #353), fixed by @jbrockmendel (gh pr #482) - Fixed problem parsing strings in %b-%Y-%d format. Reported and fixed by @jbrockmendel (gh pr #481) - Fixed problem parsing strings in the %d%B%y format. Reported by @asishm (gh issue #360), fixed by @jbrockmendel (gh pr #483) - Fixed problem parsing certain unambiguous strings when year <99 (gh pr #510). Reported by @alexwlchan (gh issue #293). - Fixed issue with parsing an unambiguous string representation of an ambiguous datetime such that if possible the correct value for fold is set. Fixes issue reported by @JordonPhillips and @pganssle (gh issue #318, #320, gh pr #517) - Fixed issue with improper rounding of fractional components. Reported by @dddmello (gh issue #427), fixed by @m-dz (gh pr #570) - Performance improvement to parser from removing certain min() calls. Reported and fixed by @jbrockmendel (gh pr #589) - Significantly refactored parser code by @jbrockmendel (gh prs #419, #436, #490, #498, #539) and @pganssle (gh prs #435, #468) - Implemented of __hash__ for relativedelta and weekday, reported and fixed by @mrigor (gh pr #389) - Implemented __abs__ for relativedelta. Reported by @binnisb and @pferreir (gh issue #350, pr #472) - Fixed relativedelta.weeks property getter and setter to work for both negative and positive values. Reported and fixed by @souliane (gh issue #459, pr #460) - Fixed issue where passing whole number floats to the months or years arguments of the relativedelta constructor would lead to errors during addition. Reported by @arouanet (gh pr #411), fixed by @lkollar (gh pr #553) - Added a pre-built tz.UTC object representing UTC (gh pr #497) - Added a cache to tz.gettz so that by default it will return the same object for identical inputs. This will change the semantics of certain operations between datetimes constructed with tzinfo=tz.gettz(...). (gh pr #628) - Changed the behavior of tz.tzutc to return a singleton (gh pr #497, #504) - Changed the behavior of tz.tzoffset to return the same object when passed the same inputs, with a corresponding performance improvement (gh pr #504) - Changed the behavior of tz.tzstr to return the same object when passed the same inputs. (gh pr #628) - Added .instance alternate constructors for tz.tzoffset and tz.tzstr, to allow the construction of a new instance if desired. (gh pr #628) - Added the tz.gettz.nocache function to allow explicit retrieval of a new instance of the relevant tzinfo. (gh pr #628) - Expand definition of tz.tzlocal equality so that the local zone is allow equality with tzoffset and tzutc. (gh pr #598) - Deprecated the idiosyncratic tzstr format mentioned in several examples but evidently designed exclusively for dateutil, and very likely not used by any current users. (gh issue #595, gh pr #606) - Added the tz.resolve_imaginary function, which generates a real date from an imaginary one, if necessary. Implemented by @Cheukting (gh issue #339, gh pr #607) - Fixed issue where the tz.tzstr constructor would erroneously succeed if passed an invalid value for tzstr. Fixed by @pablogsal (gh issue #259, gh pr #581) - Fixed issue with tz.gettz for TZ variables that start with a colon. Reported and fixed by @lapointexavier (gh pr #601) - Added a lock to tz.tzical's cache. Reported and fixed by @Unrud (gh pr #430) - Fixed an issue with fold support on certain Python 3 implementations that used the pre-3.6 pure Python implementation of datetime.replace, most notably pypy3 (gh pr #446). - Added support for VALUE=DATE-TIME for DTSTART in rrulestr. Reported by @potuz (gh issue #401) and fixed by @Unrud (gh pr #429) - Started enforcing that within VTIMEZONE, the VALUE parameter can only be omitted or DATE-TIME, per RFC 5545. Reported by @Unrud (gh pr #439) - Added support for TZID parameter for DTSTART in rrulestr. Reported and fixed by @ryanpetrello (gh issue #614, gh pr #624) - Added 'RRULE:' prefix to rrule strings generated by rrule.__str__, in compliance with the RFC. Reported by @AndrewPashkin (gh issue #86), fixed by @jarondl and @mlorant (gh pr #450) - Switched to setuptools_scm for version management, automatically calculating a version number from the git metadata. Reported by @jreback (gh issue #511), implemented by @Sulley38 (gh pr #564) - Switched setup.py to use find_packages, and started testing against pip installed versions of dateutil in CI. Fixed issue with parser import discovered by @jreback in pandas-dev/pandas#18141. (gh issue #507, pr #509) - Switched test suite to using pytest (gh pr #495) - Switched CI over to use tox. Fixed by @gaborbernat (gh pr #549) - Added a test-only dependency on freezegun. (gh pr #474) - Reduced number of CI builds on Appveyor. Fixed by @kirit93 (gh issue #529, gh pr #579) - Made xfails strict by default, so that an xpass is a failure. (gh pr #567) - Added a documentation generation stage to tox and CI. (gh pr #568) - Added an explicit warning when running python setup.py explaining how to run the test suites with pytest. Fixed by @lkollar. (gh issue #544, gh pr #548) - Added requirements-dev.txt for test dependency management (gh pr #499, #516) - Fixed code coverage metrics to account for Windows builds (gh pr #526) - Fixed code coverage metrics to NOT count xfails. Fixed by @gaborbernat (gh issue #519, gh pr #563) - Style improvement to zoneinfo.tzfile that was confusing to static type checkers. Reported and fixed by @quodlibetor (gh pr #485) - Several unused imports were removed by @jdufresne. (gh pr #486) - Switched ``isinstance(*, collections.Callable)`` to callable, which is available on all supported Python versions. Implemented by @jdufresne (gh pr #612) - Added CONTRIBUTING.md (gh pr #533) - Added AUTHORS.md (gh pr #542) - Corrected setup.py metadata to reflect author vs. maintainer, (gh issue #477, gh pr #538) - Corrected README to reflect that tests are now run in pytest. Reported and fixed by @m-dz (gh issue #556, gh pr #557) - Updated all references to RFC 2445 (iCalendar) to point to RFC 5545. Fixed by @mariocj89 (gh issue #543, gh pr #555) - Corrected parse documentation to reflect proper integer offset units, reported and fixed by @abrugh (gh pr #458) - Fixed dangling parenthesis in tzoffset documentation (gh pr #461) - Started including the license file in wheels. Reported and fixed by @jdufresne (gh pr #476) - Indentation fixes to parser docstring by @jbrockmendel (gh pr #492) - Moved many examples from the "examples" documentation into their appropriate module documentation pages. Fixed by @Tomasz-Kluczkowski and @jakec-github (gh pr #558, #561) - Fixed documentation so that the parser.isoparse documentation displays. Fixed by @alexchamberlain (gh issue #545, gh pr #560) - Refactored build and release sections and added setup instructions to CONTRIBUTING. Reported and fixed by @kynan (gh pr #562) - Cleaned up various dead links in the documentation. (gh pr #602, #608, #618) Version 2.6.1 ============= - Updated zoneinfo file to 2017b. (gh pr #395) - Added Python 3.6 to CI testing (gh pr #365) - Removed duplicate test name that was preventing a test from being run. Reported and fixed by @jdufresne (gh pr #371) - Fixed testing of folds and gaps, particularly on Windows (gh pr #392) - Fixed deprecated escape characters in regular expressions. Reported by @nascheme and @thierryba (gh issue #361), fixed by @thierryba (gh pr #358) - Many PEP8 style violations and other code smells were fixed by @jdufresne (gh prs #358, #363, #364, #366, #367, #368, #372, #374, #379, #380, #398) - Improved performance of tzutc and tzoffset objects. (gh pr #391) - Fixed issue with several time zone classes around DST transitions in any zones with +0 standard offset (e.g. Europe/London) (gh issue #321, pr #390) - Fixed issue with fuzzy parsing where tokens similar to AM/PM that are in the end skipped were dropped in the fuzzy_with_tokens list. Reported and fixed by @jbrockmendel (gh pr #332). - Fixed issue with parsing dates of the form X m YY. Reported by @jbrockmendel. (gh issue #333, pr #393) - Added support for parser weekdays with less than 3 characters. Reported by @arcadefoam (gh issue #343), fixed by @jonemo (gh pr #382) - Fixed issue with the addition and subtraction of certain relativedeltas. Reported and fixed by @kootenpv (gh issue #346, pr #347) - Fixed issue where the COUNT parameter of rrules was ignored if 0. Fixed by @mshenfield (gh pr #330), reported by @vaultah (gh issue #329). - Updated documentation to include the new tz methods. (gh pr #324) - Update documentation to reflect that the parser can raise TypeError, reported and fixed by @tomchuk (gh issue #336, pr #337) - Fixed an incorrect year in a parser doctest. Fixed by @xlotlu (gh pr #357) - Moved version information into _version.py and set up the versions more granularly. Version 2.6.0 ============= - Added PEP-495-compatible methods to address ambiguous and imaginary dates in time zones in a backwards-compatible way. Ambiguous dates and times can now be safely represented by all dateutil time zones. Many thanks to Alexander Belopolski (@abalkin) and Tim Peters @tim-one for their inputs on how to address this. Original issues reported by Yupeng and @zed (lP: 1390262, gh issues #57, #112, #249, #284, #286, prs #127, #225, #248, #264, #302). - Added new methods for working with ambiguous and imaginary dates to the tz module. datetime_ambiguous() determines if a datetime is ambiguous for a given zone and datetime_exists() determines if a datetime exists in a given zone. This works for all fold-aware datetimes, not just those provided by dateutil. (gh issue #253, gh pr #302) - Fixed an issue where dst() in Portugal in 1996 was returning the wrong value in tz.tzfile objects. Reported by @abalkin (gh issue #128, pr #225) - Fixed an issue where zoneinfo.ZoneInfoFile errors were not being properly deep-copied. (gh issue #226, pr #225) - Refactored tzwin and tzrange as a subclass of a common class, tzrangebase, as there was substantial overlapping functionality. As part of this change, tzrange and tzstr now expose a transitions() function, which returns the DST on and off transitions for a given year. (gh issue #260, pr #302) - Deprecated zoneinfo.gettz() due to confusion with tz.gettz(), in favor of get() method of zoneinfo.ZoneInfoFile objects. (gh issue #11, pr #310) - For non-character, non-stream arguments, parser.parse now raises TypeError instead of AttributeError. (gh issues #171, #269, pr #247) - Fixed an issue where tzfile objects were not properly handling dst() and tzname() when attached to datetime.time objects. Reported by @ovacephaloid. (gh issue #292, pr #309) - /usr/share/lib/zoneinfo was added to TZPATHS for compatibility with Solaris systems. Reported by @dhduvall (gh issue #276, pr #307) - tzoffset and tzrange objects now accept either a number of seconds or a datetime.timedelta() object wherever previously only a number of seconds was allowed. (gh pr #264, #277) - datetime.timedelta objects can now be added to relativedelta objects. Reported and added by Alec Nikolas Reiter (@justanr) (gh issue #282, pr #283 - Refactored relativedelta.weekday and rrule.weekday into a common base class to reduce code duplication. (gh issue #140, pr #311) - An issue where the WKST parameter was improperly rendering in str(rrule) was reported and fixed by Daniel LePage (@dplepage). (gh issue #262, pr #263) - A replace() method has been added to rrule objects by @jendas1, which creates new rrule with modified attributes, analogous to datetime.replace (gh pr #167) - Made some significant performance improvements to rrule objects in Python 2.x (gh pr #245) - All classes defining equality functions now return NotImplemented when compared to unsupported classes, rather than raising TypeError, to allow other classes to provide fallback support. (gh pr #236) - Several classes have been marked as explicitly unhashable to maintain identical behavior between Python 2 and 3. Submitted by Roy Williams (@rowillia) (gh pr #296) - Trailing whitespace in easter.py has been removed. Submitted by @OmgImAlexis (gh pr #299) - Windows-only batch files in build scripts had line endings switched to CRLF. (gh pr #237) - @adamchainz updated the documentation links to reflect that the canonical location for readthedocs links is now at .io, not .org. (gh pr #272) - Made some changes to the CI and codecov to test against newer versions of Python and pypy, and to adjust the code coverage requirements. For the moment, full pypy3 compatibility is not supported until a new release is available, due to upstream bugs in the old version affecting PEP-495 support. (gh prs #265, #266, #304, #308) - The full PGP signing key fingerprint was added to the README.md in favor of the previously used long-id. Reported by @valholl (gh issue #287, pr #304) - Updated zoneinfo to 2016i. (gh issue #298, gh pr #306) Version 2.5.3 ============= - Updated zoneinfo to 2016d - Fixed parser bug where unambiguous datetimes fail to parse when dayfirst is set to true. (gh issue #233, pr #234) - Bug in zoneinfo file on platforms such as Google App Engine which do not do not allow importing of subprocess.check_call was reported and fixed by @savraj (gh issue #239, gh pr #240) - Fixed incorrect version in documentation (gh issue #235, pr #243) Version 2.5.2 ============= - Updated zoneinfo to 2016c - Fixed parser bug where yearfirst and dayfirst parameters were not being respected when no separator was present. (gh issue #81 and #217, pr #229) Version 2.5.1 ============= - Updated zoneinfo to 2016b - Changed MANIFEST.in to explicitly include test suite in source distributions, with help from @koobs (gh issue #193, pr #194, #201, #221) - Explicitly set all line-endings to LF, except for the NEWS file, on a per-repository basis (gh pr #218) - Fixed an issue with improper caching behavior in rruleset objects (gh issue #104, pr #207) - Changed to an explicit error when rrulestr strings contain a missing BYDAY (gh issue #162, pr #211) - tzfile now correctly handles files containing leapcnt (although the leapcnt information is not actually used). Contributed by @hjoukl (gh issue #146, pr #147) - Fixed recursive import issue with tz module (gh pr #204) - Added compatibility between tzwin objects and datetime.time objects (gh issue #216, gh pr #219) - Refactored monolithic test suite by module (gh issue #61, pr #200 and #206) - Improved test coverage in the relativedelta module (gh pr #215) - Adjusted documentation to reflect possibly counter-intuitive properties of RFC-5545-compliant rrules, and other documentation improvements in the rrule module (gh issue #105, gh issue #149 - pointer to the solution by @phep, pr #213). Version 2.5.0 ============= - Updated zoneinfo to 2016a - zoneinfo_metadata file version increased to 2.0 - the updated updatezinfo.py script will work with older zoneinfo_metadata.json files, but new metadata files will not work with older updatezinfo.py versions. Additionally, we have started hosting our own mirror of the Olson databases on a GitHub pages site (https://dateutil.github.io/tzdata/) (gh pr #183) - dateutil zoneinfo tarballs now contain the full zoneinfo_metadata file used to generate them. (gh issue #27, gh pr #85) - relativedelta can now be safely subclassed without derived objects reverting to base relativedelta objects as a result of arithmetic operations. (lp:1010199, gh issue #44, pr #49) - relativedelta 'weeks' parameter can now be set and retrieved as a property of relativedelta instances. (lp: 727525, gh issue #45, pr #49) - relativedelta now explicitly supports fractional relative weeks, days, hours, minutes and seconds. Fractional values in absolute parameters (year, day, etc) are now deprecated. (gh issue #40, pr #190) - relativedelta objects previously did not use microseconds to determine of two relativedelta objects were equal. This oversight has been corrected. Contributed by @elprans (gh pr #113) - rrule now has an xafter() method for retrieving multiple recurrences after a specified date. (gh pr #38) - str(rrule) now returns an RFC2445-compliant rrule string, contributed by @schinckel and @armicron (lp:1406305, gh issue #47, prs #50, #62 and #160) - rrule performance under certain conditions has been significantly improved thanks to a patch contributed by @dekoza, based on an article by Brian Beck (@exogen) (gh pr #136) - The use of both the 'until' and 'count' parameters is now deprecated as inconsistent with RFC2445 (gh pr #62, #185) - Parsing an empty string will now raise a ValueError, rather than returning the datetime passed to the 'default' parameter. (gh issue #78, pr #187) - tzwinlocal objects now have a meaningful repr() and str() implementation (gh issue #148, prs #184 and #186) - Added equality logic for tzwin and tzwinlocal objects. (gh issue #151, pr #180, #184) - Added some flexibility in subclassing timelex, and switched the default behavior over to using string methods rather than comparing against a fixed list. (gh pr #122, #139) - An issue causing tzstr() to crash on Python 2.x was fixed. (lp: 1331576, gh issue #51, pr #55) - An issue with string encoding causing exceptions under certain circumstances when tzname() is called was fixed. (gh issue #60, #74, pr #75) - Parser issue where calling parse() on dates with no day specified when the day of the month in the default datetime (which is "today" if unspecified) is greater than the number of days in the parsed month was fixed (this issue tended to crop up between the 29th and 31st of the month, for obvious reasons) (canonical gh issue #25, pr #30, #191) - Fixed parser issue causing fuzzy_with_tokens to raise an unexpected exception in certain circumstances. Contributed by @MichaelAquilina (gh pr #91) - Fixed parser issue where years > 100 AD were incorrectly parsed. Contributed by @Bachmann1234 (gh pr #130) - Fixed parser issue where commas were not a valid separator between seconds and microseconds, preventing parsing of ISO 8601 dates. Contributed by @ryanss (gh issue #28, pr #106) - Fixed issue with tzwin encoding in locales with non-Latin alphabets (gh issue #92, pr #98) - Fixed an issue where tzwin was not being properly imported on Windows. Contributed by @labrys. (gh pr #134) - Fixed a problem causing issues importing zoneinfo in certain circumstances. Issue and solution contributed by @alexxv (gh issue #97, pr #99) - Fixed an issue where dateutil timezones were not compatible with basic time objects. One of many, many timezone related issues contributed and tested by @labrys. (gh issue #132, pr #181) - Fixed issue where tzwinlocal had an invalid utcoffset. (gh issue #135, pr #141, #142) - Fixed issue with tzwin and tzwinlocal where DST transitions were incorrectly parsed from the registry. (gh issue #143, pr #178) - updatezinfo.py no longer suppresses certain OSErrors. Contributed by @bjamesv (gh pr #164) - An issue that arose when timezone locale changes during runtime has been fixed by @carlosxl and @mjschultz (gh issue #100, prs #107, #109) - Python 3.5 was added to the supported platforms in the metadata (@tacaswell gh pr #159) and the test suites (@moreati gh pr #117). - An issue with tox failing without unittest2 installed in Python 2.6 was fixed by @moreati (gh pr #115) - Several deprecated functions were replaced in the tests by @moreati (gh pr #116) - Improved the logic in Travis and Appveyor to alleviate issues where builds were failing due to connection issues when downloading the IANA timezone files. In addition to adding our own mirror for the files (gh pr #183), the download is now retried a number of times (with a delay) (gh pr #177) - Many failing doctests were fixed by @moreati. (gh pr #120) - Many fixes to the documentation (gh pr #103, gh pr #87 from @radarhere, gh pr #154 from @gpoesia, gh pr #156 from @awsum, gh pr #168 from @ja8zyjits) - Added a code coverage tool to the CI to help improve the library. (gh pr #182) - We now have a mailing list - dateutil@python.org, graciously hosted by Python.org. Version 2.4.2 ============= - Updated zoneinfo to 2015b. - Fixed issue with parsing of tzstr on Python 2.7.x; tzstr will now be decoded if not a unicode type. gh #51 (lp:1331576), gh pr #55. - Fix a parser issue where AM and PM tokens were showing up in fuzzy date stamps, triggering inappropriate errors. gh #56 (lp: 1428895), gh pr #63. - Missing function "setcachesize" removed from zoneinfo __all__ list by @ryanss, fixing an issue with wildcard imports of dateutil.zoneinfo. (gh pr #66). - (PyPI only) Fix an issue with source distributions not including the test suite. Version 2.4.1 ============= - Added explicit check for valid hours if AM/PM is specified in parser. (gh pr #22, issue #21) - Fix bug in rrule introduced in 2.4.0 where byweekday parameter was not handled properly. (gh pr #35, issue #34) - Fix error where parser allowed some invalid dates, overwriting existing hours with the last 2-digit number in the string. (gh pr #32, issue #31) - Fix and add test for Python 2.x compatibility with boolean checking of relativedelta objects. Implemented by @nimasmi (gh pr #43) and Cédric Krier (lp: 1035038) - Replaced parse() calls with explicit datetime objects in unit tests unrelated to parser. (gh pr #36) - Changed private _byxxx from sets to sorted tuples and fixed one currently unreachable bug in _construct_byset. (gh pr #54) - Additional documentation for parser (gh pr #29, #33, #41) and rrule. - Formatting fixes to documentation of rrule and README.rst. - Updated zoneinfo to 2015a. Version 2.4.0 ============= - Fix an issue with relativedelta and freezegun (lp:1374022) - Fix tzinfo in windows for timezones without dst (lp:1010050, gh #2) - Ignore missing timezones in windows like in POSIX - Fix minimal version requirement for six (gh #6) - Many rrule changes and fixes by @pganssle (gh pull requests #13 #14 #17), including defusing some infinite loops (gh #4) Version 2.3 =========== - Cleanup directory structure, moved test.py to dateutil/tests/test.py - 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. - The package is now zip-safe, and universal-wheelable, thanks to changes in the handling of the zoneinfo file. - Fixed tzwin silently not imported on windows python2 - New maintainer, together with new hosting: GitHub, Travis, Read-The-Docs Version 2.2 =========== - Updated zoneinfo to 2013h - fuzzy_with_tokens parse addon from Christopher Corley - Bug with LANG=C fixed by Mike Gilbert Version 2.1 =========== - New maintainer - Dateutil now works on Python 2.6, 2.7 and 3.2 from same codebase (with six) - #704047: Ismael Carnales' patch for a new time format - Small bug fixes, thanks for reporters! Version 2.0 =========== - Ported to Python 3, by Brian Jones. If you need dateutil for Python 2.X, please continue using the 1.X series. - There's no such thing as a "PSF License". This source code is now made available under the Simplified BSD license. See LICENSE for details. Version 1.5 =========== - As reported by Mathieu Bridon, rrules were matching the bysecond rules incorrectly against byminute in some circumstances when the SECONDLY frequency was in use, due to a copy & paste bug. The problem has been unittested and corrected. - Adam Ryan reported a problem in the relativedelta implementation which affected the yearday parameter in the month of January specifically. This has been unittested and fixed. - Updated timezone information. Version 1.4.1 ============= - Updated timezone information. Version 1.4 =========== - Fixed another parser precision problem on conversion of decimal seconds to microseconds, as reported by Erik Brown. Now these issues are gone for real since it's not using floating point arithmetic anymore. - Fixed case where tzrange.utcoffset and tzrange.dst() might fail due to a date being used where a datetime was expected (reported and fixed by Lennart Regebro). - Prevent tzstr from introducing daylight timings in strings that didn't specify them (reported by Lennart Regebro). - Calls like gettz("GMT+3") and gettz("UTC-2") will now return the expected values, instead of the TZ variable behavior. - Fixed DST signal handling in zoneinfo files. Reported by Nicholas F. Fabry and John-Mark Gurney. Version 1.3 =========== - Fixed precision problem on conversion of decimal seconds to microseconds, as reported by Skip Montanaro. - Fixed bug in constructor of parser, and converted parser classes to new-style classes. Original report and patch by Michael Elsdörfer. - Initialize tzid and comps in tz.py, to prevent the code from ever raising a NameError (even with broken files). Johan Dahlin suggested the fix after a pyflakes run. - Version is now published in dateutil.__version__, as requested by Darren Dale. - All code is compatible with new-style division. Version 1.2 =========== - Now tzfile will round timezones to full-minutes if necessary, since Python's datetime doesn't support sub-minute offsets. Thanks to Ilpo Nyyssönen for reporting the issue. - Removed bare string exceptions, as reported and fixed by Wilfredo Sánchez Vega. - Fix bug in leap count parsing (reported and fixed by Eugene Oden). Version 1.1 =========== - Fixed rrule byyearday handling. Abramo Bagnara pointed out that RFC2445 allows negative numbers. - Fixed --prefix handling in setup.py (by Sidnei da Silva). - Now tz.gettz() returns a tzlocal instance when not given any arguments and no other timezone information is found. - Updating timezone information to version 2005q. Version 1.0 =========== - Fixed parsing of XXhXXm formatted time after day/month/year has been parsed. - Added patch by Jeffrey Harris optimizing rrule.__contains__. Version 0.9 =========== - Fixed pickling of timezone types, as reported by Andreas Köhler. - Implemented internal timezone information with binary timezone files. datautil.tz.gettz() function will now try to use the system timezone files, and fallback to the internal versions. It's also possible to ask for the internal versions directly by using dateutil.zoneinfo.gettz(). - New tzwin timezone type, allowing access to Windows internal timezones (contributed by Jeffrey Harris). - Fixed parsing of unicode date strings. - Accept parserinfo instances as the parser constructor parameter, besides parserinfo (sub)classes. - Changed weekday to spell the not-set n value as None instead of 0. - Fixed other reported bugs. Version 0.5 =========== - Removed ``FREQ_`` prefix from rrule frequency constants WARNING: this breaks compatibility with previous versions. - Fixed rrule.between() for cases where "after" is achieved before even starting, as reported by Andreas Köhler. - Fixed two digit zero-year parsing (such as 31-Dec-00), as reported by Jim Abramson, and included test case for this. - Sort exdate and rdate before iterating over them, so that it's not necessary to sort them before adding to the rruleset, as reported by Nicholas Piper. python_dateutil-4.0.0/README.rst0000644000000000000000000001364313615410400013345 0ustar00dateutil - powerful extensions to datetime ========================================== |pypi| |support| |licence| |gitter| |readthedocs| |gha| |coverage| .. |pypi| image:: https://img.shields.io/pypi/v/python-dateutil.svg?style=flat-square :target: https://pypi.org/project/python-dateutil/ :alt: pypi version .. |support| image:: https://img.shields.io/pypi/pyversions/python-dateutil.svg?style=flat-square :target: https://pypi.org/project/python-dateutil/ :alt: supported Python version .. |gha| image:: https://github.com/dateutil/dateutil/actions/workflows/validate.yml/badge.svg :target: https://github.com/dateutil/dateutil/actions :alt: github actions build status .. |coverage| image:: https://codecov.io/gh/dateutil/dateutil/branch/master/graphs/badge.svg?branch=master :target: https://codecov.io/gh/dateutil/dateutil?branch=master :alt: Code coverage .. |gitter| image:: https://badges.gitter.im/dateutil/dateutil.svg :alt: Join the chat at https://gitter.im/dateutil/dateutil :target: https://gitter.im/dateutil/dateutil .. |licence| image:: https://img.shields.io/pypi/l/python-dateutil.svg?style=flat-square :target: https://pypi.org/project/python-dateutil/ :alt: licence .. |readthedocs| image:: https://img.shields.io/readthedocs/dateutil/latest.svg?style=flat-square&label=Read%20the%20Docs :alt: Read the documentation at https://dateutil.readthedocs.io/en/latest/ :target: https://dateutil.readthedocs.io/en/latest/ 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: .. doctest:: 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 in 2003. It is maintained by: * Gustavo Niemeyer 2003-2011 * Tomi Pieviläinen 2012-2014 * Yaron de Leeuw 2014-2016 * Paul Ganssle 2015- 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. 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. .. _6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB: https://pgp.mit.edu/pks/lookup?op=vindex&search=0xCD54FCE3D964BEFB python_dateutil-4.0.0/requirements-dev.txt0000644000000000000000000000017313615410400015710 0ustar00pytest >= 3.0 pytest-cov >= 2.0.0 pytest-xdist >= 3.2.0 freezegun hypothesis >= 3.30 coverage build >= 0.3.0 attrs>=21.2.0 python_dateutil-4.0.0/tox.ini0000644000000000000000000000674213615410400013173 0ustar00[tox] envlist = py311, py312, py313, py314, py315, pypy311, coverage, docs minversion = 4.0 skip_missing_interpreters = true isolated_build = true [testenv] description = run the unit tests with pytest under {basepython} setenv = COVERAGE_FILE={toxworkdir}/.coverage.{envname} PYTEST_ADDOPTS=-n auto --dist worksteal {env:PYTEST_ADDOPTS:} passenv = DATEUTIL_MAY_CHANGE_TZ, TOXENV, CI, CODECOV_*, SYSTEM_*, AGENT_*, BUILD_*, TF_BUILD, TZ commands = python -m pytest {posargs: "{toxinidir}/tests" "{toxinidir}/docs" --cov-config="{toxinidir}/tox.ini" --cov=dateutil} deps = -rrequirements-dev.txt [testenv:coverage] description = combine coverage data and create reports deps = coverage skip_install = True changedir = {toxworkdir} setenv = COVERAGE_FILE=.coverage commands = python -m coverage erase python -m coverage combine python -m coverage report --rcfile={toxinidir}/tox.ini python -m coverage xml [testenv:codecov] description = [only run on CI]: upload coverage data to codecov (depends on coverage running first) deps = codecov skip_install = True commands = python -m codecov --file {toxworkdir}/coverage.xml [testenv:dev] description = DEV environment usedevelop = True deps = {[testenv]deps} pip commands = python -m pip list --format=columns python -c 'import sys; print(sys.executable)' [coverage:run] source = dateutil [coverage:report] skip_covered = True show_missing = True [testenv:precommit] description = Run the pre-commit hooks on all files passenv = PRE_COMMIT* deps = pre-commit commands = pre-commit install -f --install-hooks pre-commit run --all-files [testenv:tz-{fat,slim,vanguard,rearguard}] # These clone the tz repository and build it in the environment's temporary # directory, so they need network access, git, make and a C compiler. # # tz-fat and tz-slim use the main data form, compiled with `zic -b fat` or # `zic -b slim`; tz-vanguard and tz-rearguard use those data forms, compiled # with zic's default, `-b slim`. description = Run the tests against the master of the tz database basepython = python3.13 deps = -r {toxinidir}/requirements-dev.txt setenv = {[testenv]setenv} PYTHONTZPATH = {envtmpdir}/tzdir/usr/share/zoneinfo TZDIR = {envtmpdir}/tzdir/usr/share/zoneinfo fat: TZ_BLOAT = fat slim,vanguard,rearguard: TZ_BLOAT = slim fat,slim: TZ_DATAFORM = main vanguard: TZ_DATAFORM = vanguard rearguard: TZ_DATAFORM = rearguard passenv = TZ changedir = {toxworkdir} allowlist_externals = {toxinidir}/ci_tools/run_tz_master_env.sh commands = {toxinidir}/ci_tools/run_tz_master_env.sh {envtmpdir} {toxinidir} [testenv:docs] description = invoke sphinx-build to build the HTML docs, check that URIs are valid basepython = python3.13 deps = -r docs/requirements-docs.txt {[testenv]deps} commands = python -m sphinx -d "{toxworkdir}/docs_doctree" docs "{toxworkdir}/docs_out" {posargs:-W --color -bhtml} python -m sphinx -d "{toxworkdir}/docs_doctree" docs "{toxworkdir}/docs_out" {posargs:-W --color -blinkcheck} [testenv:news] description = Invoke towncrier to update the NEWS file basepython = python3.11 passenv = * deps = towncrier commands = towncrier {posargs} [testenv:build] description = Build an sdist and bdist skip_install = true passenv = * deps = build[uv] >= 1.2.0 twine commands = python -m build --installer uv --outdir dist . python -m twine check --strict dist/* python_dateutil-4.0.0/changelog.d/template.rst0000644000000000000000000000120613615410400016364 0ustar00{% for section, _ in sections.items() %} {% set underline = underlines[0] %}{% if section %}{{section}} {{ underline * section|length }}{% set underline = underlines[1] %} {% endif %} {% if sections[section] %} {% for category, val in definitions.items() if category in sections[section]%} {{ definitions[category]['name'] }} {{ underline * definitions[category]['name']|length }} {% for text, values in sections[section][category].items() %} - {{ text }} {% endfor %} {% if sections[section][category]|length == 0 %} No significant changes. {% else %} {% endif %} {% endfor %} {% else %} No significant changes. {% endif %} {% endfor %} python_dateutil-4.0.0/ci_tools/run_tz_master_env.sh0000755000000000000000000000536613615410400017577 0ustar00#!/usr/bin/env bash ### # Runs the 'tz' tox test environment, which builds the repo against the master # branch of the upstream tz database project. set -e TMP_DIR=$(readlink -f ${1}) REPO_DIR=$(readlink -f ${2}) ORIG_DIR=$(pwd) UPSTREAM_URL="https://github.com/eggert/tz.git" if [ -n "$TF_BUILD" ]; then EXTRA_TEST_ARGS=--junitxml=../unittests/TEST-tz.xml fi # Work in a temporary directory cd $TMP_DIR # Clone or update the repo DIR_EXISTS=false if [ -d tz ]; then cd tz if [[ $(git remote get-url origin) == ${UPSTREAM_URL} ]]; then git fetch origin main git reset --hard origin/main DIR_EXISTS=true else cd .. rm -rf tz fi fi if [ "$DIR_EXISTS" = false ]; then git clone ${UPSTREAM_URL} cd tz fi # Build and install the compiled zoneinfo files, as "fat" TZif files of the # "main" data form unless TZ_BLOAT and TZ_DATAFORM say otherwise TZ_BLOAT=${TZ_BLOAT:-fat} TZ_DATAFORM=${TZ_DATAFORM:-main} make ZFLAGS="-b ${TZ_BLOAT}" DATAFORM="${TZ_DATAFORM}" \ TOPDIR="${TMP_DIR}/tzdir" install cd $ORIG_DIR # Make sure that the tests will actually see the data we just built. The # tests that are about the data on TZPATH block the tzdata package # themselves (see the tz_source fixture), so that anything missing from or # unreadable in this data fails, rather than being answered by tzdata. TZ_BLOAT=${TZ_BLOAT} TZ_DATAFORM=${TZ_DATAFORM} python - <<'EOF' import os import struct import sys from dateutil import tz tzpath = os.environ["PYTHONTZPATH"] if tuple(tz.TZPATH) != (tzpath,): sys.exit("Expected TZPATH to be (%r,), got %r" % (tzpath, tz.TZPATH)) # tzdata.zi starts with a "# version" line, followed by a "# dataform" line # for anything other than the main data form. with open(os.path.join(tzpath, "tzdata.zi")) as f: header = [f.readline().strip() for _ in range(2)] print("Testing against: %s" % header[0]) dataform = "main" if header[1].startswith("# dataform "): dataform = header[1].split()[-1] if dataform != os.environ["TZ_DATAFORM"]: sys.exit( "Expected the %s data form, got %s" % (os.environ["TZ_DATAFORM"], dataform) ) print("Using the %s data form" % dataform) zone = tz.gettz("America/New_York") if zone is None or not zone._filename.startswith(tzpath): sys.exit("America/New_York was not loaded from %s: %r" % (tzpath, zone)) # Slim files have an empty version 1 data block, fat files do not. with open(zone._filename, "rb") as f: v1_timecnt = struct.unpack(">6l", f.read(44)[20:])[3] bloat = "fat" if v1_timecnt else "slim" if bloat != os.environ["TZ_BLOAT"]: sys.exit("Expected %s TZif files, got %s" % (os.environ["TZ_BLOAT"], bloat)) print("Using %s TZif files" % bloat) EOF # Run the tests python -m pytest ${REPO_DIR}/tests $EXTRA_TEST_ARGS -x python_dateutil-4.0.0/docs/Makefile0000644000000000000000000001473513615410400014251 0ustar00# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = docs_venv/bin/sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" docs_venv: python -m venv docs_venv .PHONY: venv venv: docs_venv docs_venv/bin/python -m pip install -r requirements-docs.txt docs_venv/bin/python -m pip install -U .. clean: rm -rf $(BUILDDIR)/* docs_venv html: venv $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: venv $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: venv $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: venv $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: venv $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: venv $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: venv $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/dateutil.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/dateutil.qhc" devhelp: venv $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/dateutil" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/dateutil" @echo "# devhelp" epub: venv $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: venv $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: venv $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: venv $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: venv $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: venv $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: venv $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: venv $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: venv $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: venv $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: venv $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: venv $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: venv $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: venv $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." python_dateutil-4.0.0/docs/changelog.rst0000644000000000000000000000014113615410400015254 0ustar00.. Changelog transcluded from the NEWS file ========= Changelog ========= .. include:: ../NEWS python_dateutil-4.0.0/docs/conf.py0000644000000000000000000002166213615410400014105 0ustar00#!/usr/bin/env python3 # # dateutil documentation build configuration file, created by # sphinx-quickstart on Thu Nov 20 23:18:41 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.viewcode", "sphinx.ext.intersphinx", ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'dateutil' copyright = '2019, dateutil' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. from dateutil import __version__ as VERSION # Explicitly use a relative path version = VERSION # The full version, including alpha/beta/rc tags. release = VERSION # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'dateutildoc' # -- Options for autodoc ------------------------------------------------- autodoc_mock_imports = ["ctypes.wintypes", "winreg"] # Need to mock this out specifically to avoid errors import ctypes def pointer_mock(*args, **kwargs): try: return ctypes.POINTER(*args, **kwargs) except Exception: return None ctypes.POINTER = pointer_mock sys.modules['ctypes'] = ctypes # -- Configure intersphinx ------------------------------------------------ intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'dateutil.tex', 'dateutil Documentation', 'dateutil', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'dateutil', 'dateutil Documentation', ['dateutil'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'dateutil', 'dateutil Documentation', 'dateutil', 'dateutil', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Link checking options ------------------------------------------------- linkcheck_ignore = [ # This has been spotty lately so we're adding a mirror r'https://pgp.mit.edu', # MetaCPAN frequently returns 402 for automated link checkers r"https://metacpan.org/.*", # timeanddate.com is now returning 403 for the automated link checker r"https://www\.timeanddate.com/.*", # gnu.org is intermittently unreachable from GitHub Actions runners r"https://www\.gnu\.org/.*", ] # Reduce problems with ephemeral failures linkcheck_retries = 5 python_dateutil-4.0.0/docs/easter.rst0000644000000000000000000000012513615410400014612 0ustar00====== easter ====== .. automodule:: dateutil.easter :members: :undoc-members: python_dateutil-4.0.0/docs/examples.rst0000644000000000000000000011670113615410400015155 0ustar00dateutil examples ================= .. contents:: relativedelta examples ---------------------- .. testsetup:: relativedelta from datetime import *; from dateutil.relativedelta import * import calendar NOW = datetime(2003, 9, 17, 20, 54, 47, 282310) TODAY = date(2003, 9, 17) Let's begin our trip:: >>> from datetime import *; from dateutil.relativedelta import * >>> import calendar Store some values:: >>> NOW = datetime.now() >>> TODAY = date.today() >>> NOW datetime.datetime(2003, 9, 17, 20, 54, 47, 282310) >>> TODAY datetime.date(2003, 9, 17) Next month .. doctest:: relativedelta >>> NOW+relativedelta(months=+1) datetime.datetime(2003, 10, 17, 20, 54, 47, 282310) Next month, plus one week. .. doctest:: relativedelta >>> NOW+relativedelta(months=+1, weeks=+1) datetime.datetime(2003, 10, 24, 20, 54, 47, 282310) Next month, plus one week, at 10am. .. doctest:: relativedelta >>> TODAY+relativedelta(months=+1, weeks=+1, hour=10) datetime.datetime(2003, 10, 24, 10, 0) Here is another example using an absolute relativedelta. Notice the use of year and month (both singular) which causes the values to be *replaced* in the original datetime rather than performing an arithmetic operation on them. .. doctest:: relativedelta >>> NOW+relativedelta(year=1, month=1) datetime.datetime(1, 1, 17, 20, 54, 47, 282310) Let's try the other way around. Notice that the hour setting we get in the relativedelta is relative, since it's a difference, and the weeks parameter has gone. .. doctest:: relativedelta >>> relativedelta(datetime(2003, 10, 24, 10, 0), TODAY) relativedelta(months=+1, days=+7, hours=+10) One month before one year. .. doctest:: relativedelta >>> NOW+relativedelta(years=+1, months=-1) datetime.datetime(2004, 8, 17, 20, 54, 47, 282310) How does it handle months with different numbers of days? Notice that adding one month will never cross the month boundary. .. doctest:: relativedelta >>> date(2003,1,27)+relativedelta(months=+1) datetime.date(2003, 2, 27) >>> date(2003,1,31)+relativedelta(months=+1) datetime.date(2003, 2, 28) >>> date(2003,1,31)+relativedelta(months=+2) datetime.date(2003, 3, 31) The logic for years is the same, even on leap years. .. doctest:: relativedelta >>> date(2000,2,28)+relativedelta(years=+1) datetime.date(2001, 2, 28) >>> date(2000,2,29)+relativedelta(years=+1) datetime.date(2001, 2, 28) >>> date(1999,2,28)+relativedelta(years=+1) datetime.date(2000, 2, 28) >>> date(1999,3,1)+relativedelta(years=+1) datetime.date(2000, 3, 1) >>> date(2001,2,28)+relativedelta(years=-1) datetime.date(2000, 2, 28) >>> date(2001,3,1)+relativedelta(years=-1) datetime.date(2000, 3, 1) Next friday .. doctest:: relativedelta >>> TODAY+relativedelta(weekday=FR) datetime.date(2003, 9, 19) >>> TODAY+relativedelta(weekday=calendar.FRIDAY) datetime.date(2003, 9, 19) Last friday in this month. .. doctest:: relativedelta >>> TODAY+relativedelta(day=31, weekday=FR(-1)) datetime.date(2003, 9, 26) Next wednesday (it's today!). .. doctest:: relativedelta >>> TODAY+relativedelta(weekday=WE(+1)) datetime.date(2003, 9, 17) Next wednesday, but not today. .. doctest:: relativedelta >>> TODAY+relativedelta(days=+1, weekday=WE(+1)) datetime.date(2003, 9, 24) Following `ISO year week number notation `_ find the first day of the 15th week of 1997. .. doctest:: relativedelta >>> datetime(1997,1,1)+relativedelta(day=4, weekday=MO(-1), weeks=+14) datetime.datetime(1997, 4, 7, 0, 0) How long ago has the millennium changed? .. doctest:: relativedelta :options: +NORMALIZE_WHITESPACE >>> relativedelta(NOW, date(2001,1,1)) relativedelta(years=+2, months=+8, days=+16, hours=+20, minutes=+54, seconds=+47, microseconds=+282310) How old is John? .. doctest:: relativedelta :options: +NORMALIZE_WHITESPACE >>> johnbirthday = datetime(1978, 4, 5, 12, 0) >>> relativedelta(NOW, johnbirthday) relativedelta(years=+25, months=+5, days=+12, hours=+8, minutes=+54, seconds=+47, microseconds=+282310) It works with dates too. .. doctest:: relativedelta >>> relativedelta(TODAY, johnbirthday) relativedelta(years=+25, months=+5, days=+11, hours=+12) Obtain today's date using the yearday: .. doctest:: relativedelta >>> date(2003, 1, 1)+relativedelta(yearday=260) datetime.date(2003, 9, 17) We can use today's date, since yearday should be absolute in the given year: .. doctest:: relativedelta >>> TODAY+relativedelta(yearday=260) datetime.date(2003, 9, 17) Last year it should be in the same day: .. doctest:: relativedelta >>> date(2002, 1, 1)+relativedelta(yearday=260) datetime.date(2002, 9, 17) But not in a leap year: .. doctest:: relativedelta >>> date(2000, 1, 1)+relativedelta(yearday=260) datetime.date(2000, 9, 16) We can use the non-leap year day to ignore this: .. doctest:: relativedelta >>> date(2000, 1, 1)+relativedelta(nlyearday=260) datetime.date(2000, 9, 17) rrule examples -------------- These examples were converted from the RFC. Prepare the environment. .. testsetup:: rrule from dateutil.rrule import * from dateutil.parser import * from datetime import * import pprint import sys sys.displayhook = pprint.pprint .. doctest:: rrule >>> from dateutil.rrule import * >>> from dateutil.parser import * >>> from datetime import * >>> import pprint >>> import sys >>> sys.displayhook = pprint.pprint Daily, for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(DAILY, count=10, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 9, 6, 9, 0), datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 8, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 10, 9, 0), datetime.datetime(1997, 9, 11, 9, 0)] Daily until December 24, 1997 .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(DAILY, ... dtstart=parse("19970902T090000"), ... until=parse("19971224T000000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), ... datetime.datetime(1997, 12, 21, 9, 0), datetime.datetime(1997, 12, 22, 9, 0), datetime.datetime(1997, 12, 23, 9, 0)] Every other day, 5 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(DAILY, interval=2, count=5, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 6, 9, 0), datetime.datetime(1997, 9, 8, 9, 0), datetime.datetime(1997, 9, 10, 9, 0)] Every 10 days, 5 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(DAILY, interval=10, count=5, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)] Everyday in January, for 3 years. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(YEARLY, bymonth=1, byweekday=range(7), ... dtstart=parse("19980101T090000"), ... until=parse("20000131T090000"))) [datetime.datetime(1998, 1, 1, 9, 0), datetime.datetime(1998, 1, 2, 9, 0), ... datetime.datetime(1998, 1, 30, 9, 0), datetime.datetime(1998, 1, 31, 9, 0), datetime.datetime(1999, 1, 1, 9, 0), datetime.datetime(1999, 1, 2, 9, 0), ... datetime.datetime(1999, 1, 30, 9, 0), datetime.datetime(1999, 1, 31, 9, 0), datetime.datetime(2000, 1, 1, 9, 0), datetime.datetime(2000, 1, 2, 9, 0), ... datetime.datetime(2000, 1, 30, 9, 0), datetime.datetime(2000, 1, 31, 9, 0)] Same thing, in another way. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(DAILY, bymonth=1, ... dtstart=parse("19980101T090000"), ... until=parse("20000131T090000"))) [datetime.datetime(1998, 1, 1, 9, 0), ... datetime.datetime(2000, 1, 31, 9, 0)] Weekly for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=10, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 7, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 21, 9, 0), datetime.datetime(1997, 10, 28, 9, 0), datetime.datetime(1997, 11, 4, 9, 0)] Every other week, 6 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, interval=2, count=6, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 28, 9, 0), datetime.datetime(1997, 11, 11, 9, 0)] Weekly on Tuesday and Thursday for 5 weeks. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=10, wkst=SU, byweekday=(TU,TH), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 11, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 18, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 25, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 2, 9, 0)] Every other week on Tuesday and Thursday, for 8 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, interval=2, count=8, ... wkst=SU, byweekday=(TU,TH), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 18, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 16, 9, 0)] Monthly on the 1st Friday for ten occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=10, byweekday=FR(1), ... dtstart=parse("19970905T090000"))) [datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 10, 3, 9, 0), datetime.datetime(1997, 11, 7, 9, 0), datetime.datetime(1997, 12, 5, 9, 0), datetime.datetime(1998, 1, 2, 9, 0), datetime.datetime(1998, 2, 6, 9, 0), datetime.datetime(1998, 3, 6, 9, 0), datetime.datetime(1998, 4, 3, 9, 0), datetime.datetime(1998, 5, 1, 9, 0), datetime.datetime(1998, 6, 5, 9, 0)] Every other month on the 1st and last Sunday of the month for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, interval=2, count=10, ... byweekday=(SU(1), SU(-1)), ... dtstart=parse("19970907T090000"))) [datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 28, 9, 0), datetime.datetime(1997, 11, 2, 9, 0), datetime.datetime(1997, 11, 30, 9, 0), datetime.datetime(1998, 1, 4, 9, 0), datetime.datetime(1998, 1, 25, 9, 0), datetime.datetime(1998, 3, 1, 9, 0), datetime.datetime(1998, 3, 29, 9, 0), datetime.datetime(1998, 5, 3, 9, 0), datetime.datetime(1998, 5, 31, 9, 0)] Monthly on the second to last Monday of the month for 6 months. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=6, byweekday=MO(-2), ... dtstart=parse("19970922T090000"))) [datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 20, 9, 0), datetime.datetime(1997, 11, 17, 9, 0), datetime.datetime(1997, 12, 22, 9, 0), datetime.datetime(1998, 1, 19, 9, 0), datetime.datetime(1998, 2, 16, 9, 0)] Monthly on the third to the last day of the month, for 6 months. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=6, bymonthday=-3, ... dtstart=parse("19970928T090000"))) [datetime.datetime(1997, 9, 28, 9, 0), datetime.datetime(1997, 10, 29, 9, 0), datetime.datetime(1997, 11, 28, 9, 0), datetime.datetime(1997, 12, 29, 9, 0), datetime.datetime(1998, 1, 29, 9, 0), datetime.datetime(1998, 2, 26, 9, 0)] Monthly on the 2nd and 15th of the month for 5 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=5, bymonthday=(2,15), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 15, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 15, 9, 0), datetime.datetime(1997, 11, 2, 9, 0)] Monthly on the first and last day of the month for 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=5, bymonthday=(-1,1,), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 1, 9, 0), datetime.datetime(1997, 10, 31, 9, 0), datetime.datetime(1997, 11, 1, 9, 0), datetime.datetime(1997, 11, 30, 9, 0)] Every 18 months on the 10th thru 15th of the month for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, interval=18, count=10, ... bymonthday=range(10,16), ... dtstart=parse("19970910T090000"))) [datetime.datetime(1997, 9, 10, 9, 0), datetime.datetime(1997, 9, 11, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 13, 9, 0), datetime.datetime(1997, 9, 14, 9, 0), datetime.datetime(1997, 9, 15, 9, 0), datetime.datetime(1999, 3, 10, 9, 0), datetime.datetime(1999, 3, 11, 9, 0), datetime.datetime(1999, 3, 12, 9, 0), datetime.datetime(1999, 3, 13, 9, 0)] Every Tuesday, every other month, 6 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, interval=2, count=6, byweekday=TU, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 11, 4, 9, 0)] Yearly in June and July for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=4, bymonth=(6,7), ... dtstart=parse("19970610T090000"))) [datetime.datetime(1997, 6, 10, 9, 0), datetime.datetime(1997, 7, 10, 9, 0), datetime.datetime(1998, 6, 10, 9, 0), datetime.datetime(1998, 7, 10, 9, 0)] Every 3rd year on the 1st, 100th and 200th day for 4 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=4, interval=3, byyearday=(1,100,200), ... dtstart=parse("19970101T090000"))) [datetime.datetime(1997, 1, 1, 9, 0), datetime.datetime(1997, 4, 10, 9, 0), datetime.datetime(1997, 7, 19, 9, 0), datetime.datetime(2000, 1, 1, 9, 0)] Every 20th Monday of the year, 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=3, byweekday=MO(20), ... dtstart=parse("19970519T090000"))) [datetime.datetime(1997, 5, 19, 9, 0), datetime.datetime(1998, 5, 18, 9, 0), datetime.datetime(1999, 5, 17, 9, 0)] Monday of week number 20 (where the default start of the week is Monday), 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=3, byweekno=20, byweekday=MO, ... dtstart=parse("19970512T090000"))) [datetime.datetime(1997, 5, 12, 9, 0), datetime.datetime(1998, 5, 11, 9, 0), datetime.datetime(1999, 5, 17, 9, 0)] The week number 1 may be in the last year. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=3, byweekno=1, byweekday=MO, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 12, 29, 9, 0), datetime.datetime(1999, 1, 4, 9, 0), datetime.datetime(2000, 1, 3, 9, 0)] And the week numbers greater than 51 may be in the next year. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=3, byweekno=52, byweekday=SU, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 12, 28, 9, 0), datetime.datetime(1998, 12, 27, 9, 0), datetime.datetime(2000, 1, 2, 9, 0)] Only some years have week number 53: .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=3, byweekno=53, byweekday=MO, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1998, 12, 28, 9, 0), datetime.datetime(2004, 12, 27, 9, 0), datetime.datetime(2009, 12, 28, 9, 0)] Every Friday the 13th, 4 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=4, byweekday=FR, bymonthday=13, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1998, 2, 13, 9, 0), datetime.datetime(1998, 3, 13, 9, 0), datetime.datetime(1998, 11, 13, 9, 0), datetime.datetime(1999, 8, 13, 9, 0)] Every four years, the first Tuesday after a Monday in November, 3 occurrences (U.S. Presidential Election day): .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, interval=4, count=3, bymonth=11, ... byweekday=TU, bymonthday=(2,3,4,5,6,7,8), ... dtstart=parse("19961105T090000"))) [datetime.datetime(1996, 11, 5, 9, 0), datetime.datetime(2000, 11, 7, 9, 0), datetime.datetime(2004, 11, 2, 9, 0)] The 3rd instance into the month of one of Tuesday, Wednesday or Thursday, for the next 3 months: .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=3, byweekday=(TU,WE,TH), ... bysetpos=3, dtstart=parse("19970904T090000"))) [datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 10, 7, 9, 0), datetime.datetime(1997, 11, 6, 9, 0)] The 2nd to last weekday of the month, 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=3, byweekday=(MO,TU,WE,TH,FR), ... bysetpos=-2, dtstart=parse("19970929T090000"))) [datetime.datetime(1997, 9, 29, 9, 0), datetime.datetime(1997, 10, 30, 9, 0), datetime.datetime(1997, 11, 27, 9, 0)] Every 3 hours from 9:00 AM to 5:00 PM on a specific day. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(HOURLY, interval=3, ... dtstart=parse("19970902T090000"), ... until=parse("19970902T170000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 12, 0), datetime.datetime(1997, 9, 2, 15, 0)] Every 15 minutes for 6 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MINUTELY, interval=15, count=6, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 9, 15), datetime.datetime(1997, 9, 2, 9, 30), datetime.datetime(1997, 9, 2, 9, 45), datetime.datetime(1997, 9, 2, 10, 0), datetime.datetime(1997, 9, 2, 10, 15)] Every hour and a half for 4 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MINUTELY, interval=90, count=4, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 10, 30), datetime.datetime(1997, 9, 2, 12, 0), datetime.datetime(1997, 9, 2, 13, 30)] Every 20 minutes from 9:00 AM to 4:40 PM for two days. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(MINUTELY, interval=20, count=48, ... byhour=range(9,17), byminute=(0,20,40), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 9, 20), ... datetime.datetime(1997, 9, 2, 16, 20), datetime.datetime(1997, 9, 2, 16, 40), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 3, 9, 20), ... datetime.datetime(1997, 9, 3, 16, 20), datetime.datetime(1997, 9, 3, 16, 40)] An example where the days generated makes a difference because of `wkst`. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, interval=2, count=4, ... byweekday=(TU,SU), wkst=MO, ... dtstart=parse("19970805T090000"))) [datetime.datetime(1997, 8, 5, 9, 0), datetime.datetime(1997, 8, 10, 9, 0), datetime.datetime(1997, 8, 19, 9, 0), datetime.datetime(1997, 8, 24, 9, 0)] >>> list(rrule(WEEKLY, interval=2, count=4, ... byweekday=(TU,SU), wkst=SU, ... dtstart=parse("19970805T090000"))) [datetime.datetime(1997, 8, 5, 9, 0), datetime.datetime(1997, 8, 17, 9, 0), datetime.datetime(1997, 8, 19, 9, 0), datetime.datetime(1997, 8, 31, 9, 0)] rruleset examples ----------------- Daily, for 7 days, jumping Saturday and Sunday occurrences. .. testsetup:: rruleset import datetime from dateutil.parser import parse from dateutil.rrule import rrule, rruleset from dateutil.rrule import YEARLY, MONTHLY, WEEKLY, DAILY from dateutil.rrule import MO, TU, WE, TH, FR, SA, SU import pprint import sys sys.displayhook = pprint.pprint .. doctest:: rruleset :options: +NORMALIZE_WHITESPACE >>> set = rruleset() >>> set.rrule(rrule(DAILY, count=7, ... dtstart=parse("19970902T090000"))) >>> set.exrule(rrule(YEARLY, byweekday=(SA,SU), ... dtstart=parse("19970902T090000"))) >>> list(set) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 9, 8, 9, 0)] Weekly, for 4 weeks, plus one time on day 7, and not on day 16. .. doctest:: rruleset :options: +NORMALIZE_WHITESPACE >>> set = rruleset() >>> set.rrule(rrule(WEEKLY, count=4, ... dtstart=parse("19970902T090000"))) >>> set.rdate(datetime.datetime(1997, 9, 7, 9, 0)) >>> set.exdate(datetime.datetime(1997, 9, 16, 9, 0)) >>> list(set) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 23, 9, 0)] rrulestr() examples ------------------- Every 10 days, 5 occurrences. .. testsetup:: rrulestr from dateutil.parser import parse from dateutil.rrule import rruleset, rrulestr import pprint import sys sys.displayhook = pprint.pprint .. doctest:: rrulestr :options: +NORMALIZE_WHITESPACE >>> list(rrulestr(""" ... DTSTART:19970902T090000 ... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5 ... """)) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)] Same thing, but passing only the `RRULE` value. .. doctest:: rrulestr :options: +NORMALIZE_WHITESPACE >>> list(rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5", ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)] Notice that when using a single rule, it returns an `rrule` instance, unless `forceset` was used. .. doctest:: rrulestr :options: +ELLIPSIS >>> rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5") >>> rrulestr(""" ... DTSTART:19970902T090000 ... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5 ... """) >>> rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5", forceset=True) But when an `rruleset` is needed, it is automatically used. .. doctest:: rrulestr :options: +ELLIPSIS >>> rrulestr(""" ... DTSTART:19970902T090000 ... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5 ... RRULE:FREQ=DAILY;INTERVAL=5;COUNT=3 ... """) parse examples -------------- The following code will prepare the environment: .. doctest:: tz >>> from dateutil.parser import * >>> from dateutil.tz import * >>> from datetime import * >>> TZOFFSETS = {"BRST": -10800} >>> BRSTTZ = tzoffset("BRST", -10800) >>> DEFAULT = datetime(2003, 9, 25) Some simple examples based on the `date` command, using the `ZOFFSET` dictionary to provide the BRST timezone offset. .. doctest:: tz :options: +NORMALIZE_WHITESPACE >>> parse("Thu Sep 25 10:36:28 BRST 2003", tzinfos=TZOFFSETS) datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800)) >>> parse("2003 10:36:28 BRST 25 Sep Thu", tzinfos=TZOFFSETS) datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800)) Notice that since BRST is my local timezone, parsing it without further timezone settings will yield a `tzlocal` timezone. .. doctest:: tz >>> parse("Thu Sep 25 10:36:28 BRST 2003") datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzlocal()) We can also ask to ignore the timezone explicitly: .. doctest:: tz >>> parse("Thu Sep 25 10:36:28 BRST 2003", ignoretz=True) datetime.datetime(2003, 9, 25, 10, 36, 28) That's the same as processing a string without timezone: .. doctest:: tz >>> parse("Thu Sep 25 10:36:28 2003") datetime.datetime(2003, 9, 25, 10, 36, 28) Without the year, but passing our `DEFAULT` datetime to return the same year, no mattering what year we currently are in: .. doctest:: tz >>> parse("Thu Sep 25 10:36:28", default=DEFAULT) datetime.datetime(2003, 9, 25, 10, 36, 28) Strip it further: .. doctest:: tz >>> parse("Thu Sep 10:36:28", default=DEFAULT) datetime.datetime(2003, 9, 25, 10, 36, 28) >>> parse("Thu 10:36:28", default=DEFAULT) datetime.datetime(2003, 9, 25, 10, 36, 28) >>> parse("Thu 10:36", default=DEFAULT) datetime.datetime(2003, 9, 25, 10, 36) >>> parse("10:36", default=DEFAULT) datetime.datetime(2003, 9, 25, 10, 36) Strip in a different way: .. doctest:: tz >>> parse("Thu Sep 25 2003") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("Sep 25 2003") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("Sep 2003", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) >>> parse("Sep", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) >>> parse("2003", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) Another format, based on `date -R` (RFC822): .. doctest:: tz :options: +NORMALIZE_WHITESPACE >>> parse("Thu, 25 Sep 2003 10:49:41 -0300") datetime.datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, -10800)) ISO format: .. doctest:: tz :options: +NORMALIZE_WHITESPACE >>> parse("2003-09-25T10:49:41.5-03:00") datetime.datetime(2003, 9, 25, 10, 49, 41, 500000, tzinfo=tzoffset(None, -10800)) Some variations: .. doctest:: tz >>> parse("2003-09-25T10:49:41") datetime.datetime(2003, 9, 25, 10, 49, 41) >>> parse("2003-09-25T10:49") datetime.datetime(2003, 9, 25, 10, 49) >>> parse("2003-09-25T10") datetime.datetime(2003, 9, 25, 10, 0) >>> parse("2003-09-25") datetime.datetime(2003, 9, 25, 0, 0) ISO format, without separators: .. doctest:: tz :options: +NORMALIZE_WHITESPACE >>> parse("20030925T104941.5-0300") datetime.datetime(2003, 9, 25, 10, 49, 41, 500000, tzinfo=tzoffset(None, -10800)) >>> parse("20030925T104941-0300") datetime.datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, -10800)) >>> parse("20030925T104941") datetime.datetime(2003, 9, 25, 10, 49, 41) >>> parse("20030925T1049") datetime.datetime(2003, 9, 25, 10, 49) >>> parse("20030925T10") datetime.datetime(2003, 9, 25, 10, 0) >>> parse("20030925") datetime.datetime(2003, 9, 25, 0, 0) Everything together. .. doctest:: tz >>> parse("199709020900") datetime.datetime(1997, 9, 2, 9, 0) >>> parse("19970902090059") datetime.datetime(1997, 9, 2, 9, 0, 59) Different date orderings: .. doctest:: tz >>> parse("2003-09-25") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("2003-Sep-25") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("25-Sep-2003") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("Sep-25-2003") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("09-25-2003") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("25-09-2003") datetime.datetime(2003, 9, 25, 0, 0) Check some ambiguous dates: .. doctest:: tz >>> parse("10-09-2003") datetime.datetime(2003, 10, 9, 0, 0) >>> parse("10-09-2003", dayfirst=True) datetime.datetime(2003, 9, 10, 0, 0) >>> parse("10-09-03") datetime.datetime(2003, 10, 9, 0, 0) >>> parse("10-09-03", yearfirst=True) datetime.datetime(2010, 9, 3, 0, 0) Other date separators are allowed: .. doctest:: tz >>> parse("2003.Sep.25") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("2003/09/25") datetime.datetime(2003, 9, 25, 0, 0) Even with spaces: .. doctest:: tz >>> parse("2003 Sep 25") datetime.datetime(2003, 9, 25, 0, 0) >>> parse("2003 09 25") datetime.datetime(2003, 9, 25, 0, 0) Hours with letters work: .. doctest:: tz >>> parse("10h36m28.5s", default=DEFAULT) datetime.datetime(2003, 9, 25, 10, 36, 28, 500000) >>> parse("01s02h03m", default=DEFAULT) datetime.datetime(2003, 9, 25, 2, 3, 1) >>> parse("01h02m03", default=DEFAULT) datetime.datetime(2003, 9, 25, 1, 2, 3) >>> parse("01h02", default=DEFAULT) datetime.datetime(2003, 9, 25, 1, 2) >>> parse("01h02s", default=DEFAULT) datetime.datetime(2003, 9, 25, 1, 0, 2) With AM/PM: .. doctest:: tz >>> parse("10h am", default=DEFAULT) datetime.datetime(2003, 9, 25, 10, 0) >>> parse("10pm", default=DEFAULT) datetime.datetime(2003, 9, 25, 22, 0) >>> parse("12:00am", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) >>> parse("12pm", default=DEFAULT) datetime.datetime(2003, 9, 25, 12, 0) Some special treating for ''pertain'' relations: .. doctest:: tz >>> parse("Sep 03", default=DEFAULT) datetime.datetime(2003, 9, 3, 0, 0) >>> parse("Sep of 03", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) Fuzzy parsing: .. doctest:: tz :options: +NORMALIZE_WHITESPACE >>> s = "Today is 25 of September of 2003, exactly " \ ... "at 10:49:41 with timezone -03:00." >>> parse(s, fuzzy=True) datetime.datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, -10800)) Other random formats: .. doctest:: tz >>> parse("Wed, July 10, '96") datetime.datetime(1996, 7, 10, 0, 0) >>> parse("1996.07.10 AD at 15:08:56 PDT", ignoretz=True) datetime.datetime(1996, 7, 10, 15, 8, 56) >>> parse("Tuesday, April 12, 1952 AD 3:30:42pm PST", ignoretz=True) datetime.datetime(1952, 4, 12, 15, 30, 42) >>> parse("November 5, 1994, 8:15:30 am EST", ignoretz=True) datetime.datetime(1994, 11, 5, 8, 15, 30) >>> parse("3rd of May 2001") datetime.datetime(2001, 5, 3, 0, 0) >>> parse("5:50 A.M. on June 13, 1990") datetime.datetime(1990, 6, 13, 5, 50) Override parserinfo with a custom parserinfo .. doctest:: tz >>> from dateutil.parser import parse, parserinfo >>> class CustomParserInfo(parserinfo): ... # e.g. edit a property of parserinfo to allow a custom 12 hour format ... AMPM = [("am", "a", "xm"), ("pm", "p")] >>> parse('2018-06-08 12:06:58 XM', parserinfo=CustomParserInfo()) datetime.datetime(2018, 6, 8, 0, 6, 58) tzutc examples -------------- .. doctest:: tzutc >>> from datetime import * >>> from dateutil import tz >>> datetime.now() datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) >>> datetime.now(tz.UTC) datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) >>> datetime.now(tz.UTC).tzname() 'UTC' tzoffset examples ----------------- .. doctest:: tzoffset :options: +NORMALIZE_WHITESPACE >>> from datetime import * >>> from dateutil.tz import * >>> datetime.now(tzoffset("BRST", -10800)) datetime.datetime(2003, 9, 27, 9, 52, 43, 624904, tzinfo=tzinfo=tzoffset('BRST', -10800)) >>> datetime.now(tzoffset("BRST", -10800)).tzname() 'BRST' >>> datetime.now(tzoffset("BRST", -10800)).astimezone(UTC) datetime.datetime(2003, 9, 27, 12, 53, 11, 446419, tzinfo=tzutc()) tzlocal examples ---------------- .. doctest:: tzlocal >>> from datetime import * >>> from dateutil.tz import * >>> datetime.now(tzlocal()) datetime.datetime(2003, 9, 27, 10, 1, 43, 673605, tzinfo=tzlocal()) >>> datetime.now(tzlocal()).tzname() 'BRST' >>> datetime.now(tzlocal()).astimezone(tzoffset(None, 0)) datetime.datetime(2003, 9, 27, 13, 3, 0, 11493, tzinfo=tzoffset(None, 0)) tzstr examples -------------- Here are examples of the recognized formats: * `EST5EDT` * `EST5EDT4,M4.1.0/02:00:00,M10-5-0/02:00` * `EST5EDT4,95/02:00:00,298/02:00` * `EST5EDT4,J96/02:00:00,J299/02:00` Notice that if daylight information is not present, but a daylight abbreviation was provided, `tzstr` will follow the convention of using the first sunday of April to start daylight saving, and the last sunday of October to end it. If start or end time is not present, 2AM will be used, and if the daylight offset is not present, the standard offset plus one hour will be used. This convention is the same as used in the GNU libc. This also means that some of the above examples are exactly equivalent, and all of these examples are equivalent in the year of 2003. Here is the example mentioned in the [https://docs.python.org/3/library/time.html time module documentation]. .. testsetup:: tzstr import os import time from datetime import datetime from dateutil.tz import tzstr .. doctest:: tzstr >>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0' >>> time.tzset() >>> time.strftime('%X %x %Z') '02:07:36 05/08/03 EDT' >>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0' >>> time.tzset() >>> time.strftime('%X %x %Z') '16:08:12 05/08/03 AEST' And here is an example showing the same information using `tzstr`, without touching system settings. .. doctest:: tzstr >>> tz1 = tzstr('EST+05EDT,M4.1.0,M10.5.0') >>> tz2 = tzstr('AEST-10AEDT-11,M10.5.0,M3.5.0') >>> dt = datetime(2003, 5, 8, 2, 7, 36, tzinfo=tz1) >>> dt.strftime('%X %x %Z') '02:07:36 05/08/03 EDT' >>> dt.astimezone(tz2).strftime('%X %x %Z') '16:07:36 05/08/03 AEST' Are these really equivalent? .. doctest:: tzstr >>> tzstr('EST5EDT') == tzstr('EST5EDT,M4.1.0,M10.5.0') True Check the daylight limit. .. doctest:: tzstr >>> tz = tzstr('EST+05EDT,M4.1.0,M10.5.0') >>> datetime(2003, 4, 6, 1, 59, tzinfo=tz).tzname() 'EST' >>> datetime(2003, 4, 6, 2, 00, tzinfo=tz).tzname() 'EDT' >>> datetime(2003, 10, 26, 0, 59, tzinfo=tz).tzname() 'EDT' >>> datetime(2003, 10, 26, 2, 00, tzinfo=tz).tzname() 'EST' tzrange examples ---------------- .. testsetup:: tzrange from dateutil.tz import tzrange, tzstr .. doctest:: tzrange >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") True >>> from dateutil.relativedelta import * >>> range1 = tzrange("EST", -18000, "EDT") >>> range2 = tzrange("EST", -18000, "EDT", -14400, ... relativedelta(hours=+2, month=4, day=1, ... weekday=SU(+1)), ... relativedelta(hours=+1, month=10, day=31, ... weekday=SU(-1))) >>> tzstr('EST5EDT') == range1 == range2 True Notice a minor detail in the last example: while the DST should end at 2AM, the delta will catch 1AM. That's because the daylight saving time should end at 2AM standard time (the difference between STD and DST is 1h in the given example) instead of the DST time. That's how the `tzinfo` subtypes should deal with the extra hour that happens when going back to the standard time. Check [https://docs.python.org/3/library/datetime.html#datetime.tzinfo tzinfo documentation] for more information. tzfile examples --------------- .. testsetup:: tzfile from datetime import datetime from dateutil.tz import tzfile, UTC .. doctest:: tzfile :options: +NORMALIZE_WHITESPACE >>> tz = tzfile("/etc/localtime") >>> datetime.now(tz) datetime.datetime(2003, 9, 27, 12, 3, 48, 392138, tzinfo=tzfile('/etc/localtime')) >>> datetime.now(tz).astimezone(UTC) datetime.datetime(2003, 9, 27, 15, 3, 53, 70863, tzinfo=tzutc()) >>> datetime.now(tz).tzname() 'BRST' >>> datetime(2003, 1, 1, tzinfo=tz).tzname() 'BRDT' Check the daylight limit. .. doctest:: tzfile >>> tz = tzfile('/usr/share/zoneinfo/EST5EDT') >>> datetime(2003, 4, 6, 1, 59, tzinfo=tz).tzname() 'EST' >>> datetime(2003, 4, 6, 2, 00, tzinfo=tz).tzname() 'EDT' >>> datetime(2003, 10, 26, 0, 59, tzinfo=tz).tzname() 'EDT' >>> datetime(2003, 10, 26, 1, 00, tzinfo=tz).tzname() 'EST' tzical examples --------------- Here is a sample file extracted from the RFC. This file defines the `EST5EDT` timezone, and will be used in the following example. .. include:: samples/EST5EDT.ics :literal: And here is an example exploring a `tzical` type: .. doctest:: tzfile >>> from dateutil.tz import *; from datetime import * >>> tz = tzical('samples/EST5EDT.ics') >>> tz.keys() ['US-Eastern'] >>> est = tz.get('US-Eastern') >>> est >>> datetime.now(est) datetime.datetime(2003, 10, 6, 19, 44, 18, 667987, tzinfo=) >>> est == tz.get() True Let's check the daylight ranges, as usual: .. doctest:: tzfile >>> datetime(2003, 4, 6, 1, 59, tzinfo=est).tzname() 'EST' >>> datetime(2003, 4, 6, 2, 00, tzinfo=est).tzname() 'EDT' >>> datetime(2003, 10, 26, 0, 59, tzinfo=est).tzname() 'EDT' >>> datetime(2003, 10, 26, 1, 00, tzinfo=est).tzname() 'EST' tzwin examples -------------- .. doctest:: tzwin >>> tz = tzwin("E. South America Standard Time") tzwinlocal examples ------------------- .. doctest:: tzwinlocal >>> tz = tzwinlocal() # vim:ts=4:sw=4:et python_dateutil-4.0.0/docs/index.rst0000644000000000000000000000116513615410400014443 0ustar00.. dateutil documentation master file, created by sphinx-quickstart on Thu Nov 20 23:18:41 2014. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. .. include:: ../README.rst Documentation ============= Contents: .. toctree:: :maxdepth: 1 Overview Changelog Examples Exercises .. toctree:: :maxdepth: 2 easter parser relativedelta rrule tz tz.win utils zoneinfo Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python_dateutil-4.0.0/docs/make.bat0000644000000000000000000001506113615410400014207 0ustar00@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\dateutil.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\dateutil.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end python_dateutil-4.0.0/docs/parser.rst0000644000000000000000000000061513615410400014627 0ustar00====== parser ====== .. automodule:: dateutil.parser Functions --------- .. automethod:: dateutil.parser.parse .. automethod:: dateutil.parser.isoparse Classes ------- .. autoclass:: dateutil.parser.parserinfo :members: :undoc-members: Warnings and Exceptions ----------------------- .. autoclass:: dateutil.parser.ParserError .. autoclass:: dateutil.parser.UnknownTimezoneWarning python_dateutil-4.0.0/docs/relativedelta.rst0000644000000000000000000001271013615410400016157 0ustar00============= relativedelta ============= .. automodule:: dateutil.relativedelta :members: :undoc-members: .. testsetup:: relativedelta Examples -------- >>> from datetime import *; from dateutil.relativedelta import * >>> import calendar >>> NOW = datetime(2003, 9, 17, 20, 54, 47, 282310) >>> TODAY = date(2003, 9, 17) Let's begin our trip:: >>> from datetime import *; from dateutil.relativedelta import * >>> import calendar Store some values:: >>> NOW = datetime.now() >>> TODAY = date.today() >>> NOW datetime.datetime(2003, 9, 17, 20, 54, 47, 282310) >>> TODAY datetime.date(2003, 9, 17) Next month .. doctest:: relativedelta >>> NOW+relativedelta(months=+1) datetime.datetime(2003, 10, 17, 20, 54, 47, 282310) Next month, plus one week. .. doctest:: relativedelta >>> NOW+relativedelta(months=+1, weeks=+1) datetime.datetime(2003, 10, 24, 20, 54, 47, 282310) Next month, plus one week, at 10am. .. doctest:: relativedelta >>> TODAY+relativedelta(months=+1, weeks=+1, hour=10) datetime.datetime(2003, 10, 24, 10, 0) Here is another example using an absolute relativedelta. Notice the use of year and month (both singular) which causes the values to be *replaced* in the original datetime rather than performing an arithmetic operation on them. .. doctest:: relativedelta >>> NOW+relativedelta(year=1, month=1) datetime.datetime(1, 1, 17, 20, 54, 47, 282310) Let's try the other way around. Notice that the hour setting we get in the relativedelta is relative, since it's a difference, and the weeks parameter has gone. .. doctest:: relativedelta >>> relativedelta(datetime(2003, 10, 24, 10, 0), TODAY) relativedelta(months=+1, days=+7, hours=+10) One month before one year. .. doctest:: relativedelta >>> NOW+relativedelta(years=+1, months=-1) datetime.datetime(2004, 8, 17, 20, 54, 47, 282310) How does it handle months with different numbers of days? Notice that adding one month will never cross the month boundary. .. doctest:: relativedelta >>> date(2003,1,27)+relativedelta(months=+1) datetime.date(2003, 2, 27) >>> date(2003,1,31)+relativedelta(months=+1) datetime.date(2003, 2, 28) >>> date(2003,1,31)+relativedelta(months=+2) datetime.date(2003, 3, 31) The logic for years is the same, even on leap years. If the result falls on a day after the last one of the month, the last day of the month is used instead. .. doctest:: >>> date(2003,1,30)+relativedelta(months=+1) datetime.date(2003, 2, 28) >>> date(2003,5,31)+relativedelta(months=-1) datetime.date(2003, 4, 30) .. doctest:: relativedelta >>> date(2000,2,28)+relativedelta(years=+1) datetime.date(2001, 2, 28) >>> date(2000,2,29)+relativedelta(years=+1) datetime.date(2001, 2, 28) >>> date(1999,2,28)+relativedelta(years=+1) datetime.date(2000, 2, 28) >>> date(1999,3,1)+relativedelta(years=+1) datetime.date(2000, 3, 1) >>> date(2001,2,28)+relativedelta(years=-1) datetime.date(2000, 2, 28) >>> date(2001,3,1)+relativedelta(years=-1) datetime.date(2000, 3, 1) Next friday .. doctest:: relativedelta >>> TODAY+relativedelta(weekday=FR) datetime.date(2003, 9, 19) >>> TODAY+relativedelta(weekday=calendar.FRIDAY) datetime.date(2003, 9, 19) Last friday in this month. .. doctest:: relativedelta >>> TODAY+relativedelta(day=31, weekday=FR(-1)) datetime.date(2003, 9, 26) Next wednesday (it's today!). .. doctest:: relativedelta >>> TODAY+relativedelta(weekday=WE(+1)) datetime.date(2003, 9, 17) Next wednesday, but not today. .. doctest:: relativedelta >>> TODAY+relativedelta(days=+1, weekday=WE(+1)) datetime.date(2003, 9, 24) Following `ISO year week number notation `_ find the first day of the 15th week of 1997. .. doctest:: relativedelta >>> datetime(1997,1,1)+relativedelta(day=4, weekday=MO(-1), weeks=+14) datetime.datetime(1997, 4, 7, 0, 0) How long ago has the millennium changed? .. doctest:: relativedelta :options: +NORMALIZE_WHITESPACE >>> relativedelta(NOW, date(2001,1,1)) relativedelta(years=+2, months=+8, days=+16, hours=+20, minutes=+54, seconds=+47, microseconds=+282310) How old is John? .. doctest:: relativedelta :options: +NORMALIZE_WHITESPACE >>> johnbirthday = datetime(1978, 4, 5, 12, 0) >>> relativedelta(NOW, johnbirthday) relativedelta(years=+25, months=+5, days=+12, hours=+8, minutes=+54, seconds=+47, microseconds=+282310) It works with dates too. .. doctest:: relativedelta >>> relativedelta(TODAY, johnbirthday) relativedelta(years=+25, months=+5, days=+11, hours=+12) Obtain today's date using the yearday: .. doctest:: relativedelta >>> date(2003, 1, 1)+relativedelta(yearday=260) datetime.date(2003, 9, 17) We can use today's date, since yearday should be absolute in the given year: .. doctest:: relativedelta >>> TODAY+relativedelta(yearday=260) datetime.date(2003, 9, 17) Last year it should be in the same day: .. doctest:: relativedelta >>> date(2002, 1, 1)+relativedelta(yearday=260) datetime.date(2002, 9, 17) But not in a leap year: .. doctest:: relativedelta >>> date(2000, 1, 1)+relativedelta(yearday=260) datetime.date(2000, 9, 16) We can use the non-leap year day to ignore this: .. doctest:: relativedelta >>> date(2000, 1, 1)+relativedelta(nlyearday=260) datetime.date(2000, 9, 17) python_dateutil-4.0.0/docs/requirements-docs.txt0000644000000000000000000000010413615410400017004 0ustar00Sphinx>=1.7.3,!=1.8.0 sphinx_rtd_theme>=0.3.0 readme-renderer>=21.0 python_dateutil-4.0.0/docs/rrule.rst0000644000000000000000000005051713615410400014472 0ustar00===== rrule ===== .. automodule:: dateutil.rrule :undoc-members: Classes ------- .. autoclass:: rrule :members: :undoc-members: :inherited-members: .. autoclass:: rruleset :members: :undoc-members: :inherited-members: Functions --------- .. autofunction:: rrulestr rrule examples -------------- These examples were converted from the RFC. Prepare the environment. .. testsetup:: rrule from dateutil.rrule import * from dateutil.parser import * from datetime import * import pprint import sys sys.displayhook = pprint.pprint .. doctest:: rrule >>> from dateutil.rrule import * >>> from dateutil.parser import * >>> from datetime import * >>> import pprint >>> import sys >>> sys.displayhook = pprint.pprint Daily, for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(DAILY, count=10, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 9, 6, 9, 0), datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 8, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 10, 9, 0), datetime.datetime(1997, 9, 11, 9, 0)] Daily until December 24, 1997 .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(DAILY, ... dtstart=parse("19970902T090000"), ... until=parse("19971224T000000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), ... datetime.datetime(1997, 12, 21, 9, 0), datetime.datetime(1997, 12, 22, 9, 0), datetime.datetime(1997, 12, 23, 9, 0)] Every other day, 5 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(DAILY, interval=2, count=5, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 6, 9, 0), datetime.datetime(1997, 9, 8, 9, 0), datetime.datetime(1997, 9, 10, 9, 0)] Every 10 days, 5 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(DAILY, interval=10, count=5, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)] Everyday in January, for 3 years. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(YEARLY, bymonth=1, byweekday=range(7), ... dtstart=parse("19980101T090000"), ... until=parse("20000131T090000"))) [datetime.datetime(1998, 1, 1, 9, 0), datetime.datetime(1998, 1, 2, 9, 0), ... datetime.datetime(1998, 1, 30, 9, 0), datetime.datetime(1998, 1, 31, 9, 0), datetime.datetime(1999, 1, 1, 9, 0), datetime.datetime(1999, 1, 2, 9, 0), ... datetime.datetime(1999, 1, 30, 9, 0), datetime.datetime(1999, 1, 31, 9, 0), datetime.datetime(2000, 1, 1, 9, 0), datetime.datetime(2000, 1, 2, 9, 0), ... datetime.datetime(2000, 1, 30, 9, 0), datetime.datetime(2000, 1, 31, 9, 0)] Same thing, in another way. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(DAILY, bymonth=1, ... dtstart=parse("19980101T090000"), ... until=parse("20000131T090000"))) [datetime.datetime(1998, 1, 1, 9, 0), ... datetime.datetime(2000, 1, 31, 9, 0)] Weekly for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=10, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 7, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 21, 9, 0), datetime.datetime(1997, 10, 28, 9, 0), datetime.datetime(1997, 11, 4, 9, 0)] Every other week, 6 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, interval=2, count=6, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 28, 9, 0), datetime.datetime(1997, 11, 11, 9, 0)] Weekly on Tuesday and Thursday for 5 weeks. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=10, wkst=SU, byweekday=(TU,TH), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 11, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 18, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 25, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 2, 9, 0)] Every other week on Tuesday and Thursday, for 8 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, interval=2, count=8, ... wkst=SU, byweekday=(TU,TH), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 18, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 14, 9, 0), datetime.datetime(1997, 10, 16, 9, 0)] Monthly on the 1st Friday for ten occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=10, byweekday=FR(1), ... dtstart=parse("19970905T090000"))) [datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 10, 3, 9, 0), datetime.datetime(1997, 11, 7, 9, 0), datetime.datetime(1997, 12, 5, 9, 0), datetime.datetime(1998, 1, 2, 9, 0), datetime.datetime(1998, 2, 6, 9, 0), datetime.datetime(1998, 3, 6, 9, 0), datetime.datetime(1998, 4, 3, 9, 0), datetime.datetime(1998, 5, 1, 9, 0), datetime.datetime(1998, 6, 5, 9, 0)] Every other month on the 1st and last Sunday of the month for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, interval=2, count=10, ... byweekday=(SU(1), SU(-1)), ... dtstart=parse("19970907T090000"))) [datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 28, 9, 0), datetime.datetime(1997, 11, 2, 9, 0), datetime.datetime(1997, 11, 30, 9, 0), datetime.datetime(1998, 1, 4, 9, 0), datetime.datetime(1998, 1, 25, 9, 0), datetime.datetime(1998, 3, 1, 9, 0), datetime.datetime(1998, 3, 29, 9, 0), datetime.datetime(1998, 5, 3, 9, 0), datetime.datetime(1998, 5, 31, 9, 0)] Monthly on the second to last Monday of the month for 6 months. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=6, byweekday=MO(-2), ... dtstart=parse("19970922T090000"))) [datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 20, 9, 0), datetime.datetime(1997, 11, 17, 9, 0), datetime.datetime(1997, 12, 22, 9, 0), datetime.datetime(1998, 1, 19, 9, 0), datetime.datetime(1998, 2, 16, 9, 0)] Monthly on the third to the last day of the month, for 6 months. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=6, bymonthday=-3, ... dtstart=parse("19970928T090000"))) [datetime.datetime(1997, 9, 28, 9, 0), datetime.datetime(1997, 10, 29, 9, 0), datetime.datetime(1997, 11, 28, 9, 0), datetime.datetime(1997, 12, 29, 9, 0), datetime.datetime(1998, 1, 29, 9, 0), datetime.datetime(1998, 2, 26, 9, 0)] Monthly on the 2nd and 15th of the month for 5 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=5, bymonthday=(2,15), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 15, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 15, 9, 0), datetime.datetime(1997, 11, 2, 9, 0)] Monthly on the first and last day of the month for 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=5, bymonthday=(-1,1,), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 10, 1, 9, 0), datetime.datetime(1997, 10, 31, 9, 0), datetime.datetime(1997, 11, 1, 9, 0), datetime.datetime(1997, 11, 30, 9, 0)] Every 18 months on the 10th thru 15th of the month for 10 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, interval=18, count=10, ... bymonthday=range(10,16), ... dtstart=parse("19970910T090000"))) [datetime.datetime(1997, 9, 10, 9, 0), datetime.datetime(1997, 9, 11, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 13, 9, 0), datetime.datetime(1997, 9, 14, 9, 0), datetime.datetime(1997, 9, 15, 9, 0), datetime.datetime(1999, 3, 10, 9, 0), datetime.datetime(1999, 3, 11, 9, 0), datetime.datetime(1999, 3, 12, 9, 0), datetime.datetime(1999, 3, 13, 9, 0)] Every Tuesday, every other month, 6 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, interval=2, count=6, byweekday=TU, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 16, 9, 0), datetime.datetime(1997, 9, 23, 9, 0), datetime.datetime(1997, 9, 30, 9, 0), datetime.datetime(1997, 11, 4, 9, 0)] Yearly in June and July for 4 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=4, bymonth=(6,7), ... dtstart=parse("19970610T090000"))) [datetime.datetime(1997, 6, 10, 9, 0), datetime.datetime(1997, 7, 10, 9, 0), datetime.datetime(1998, 6, 10, 9, 0), datetime.datetime(1998, 7, 10, 9, 0)] Every 3rd year on the 1st, 100th and 200th day for 4 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=4, interval=3, byyearday=(1,100,200), ... dtstart=parse("19970101T090000"))) [datetime.datetime(1997, 1, 1, 9, 0), datetime.datetime(1997, 4, 10, 9, 0), datetime.datetime(1997, 7, 19, 9, 0), datetime.datetime(2000, 1, 1, 9, 0)] Every 20th Monday of the year, 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=3, byweekday=MO(20), ... dtstart=parse("19970519T090000"))) [datetime.datetime(1997, 5, 19, 9, 0), datetime.datetime(1998, 5, 18, 9, 0), datetime.datetime(1999, 5, 17, 9, 0)] Monday of week number 20 (where the default start of the week is Monday), 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=3, byweekno=20, byweekday=MO, ... dtstart=parse("19970512T090000"))) [datetime.datetime(1997, 5, 12, 9, 0), datetime.datetime(1998, 5, 11, 9, 0), datetime.datetime(1999, 5, 17, 9, 0)] The week number 1 may be in the last year. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=3, byweekno=1, byweekday=MO, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 12, 29, 9, 0), datetime.datetime(1999, 1, 4, 9, 0), datetime.datetime(2000, 1, 3, 9, 0)] And the week numbers greater than 51 may be in the next year. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=3, byweekno=52, byweekday=SU, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 12, 28, 9, 0), datetime.datetime(1998, 12, 27, 9, 0), datetime.datetime(2000, 1, 2, 9, 0)] Only some years have week number 53: .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, count=3, byweekno=53, byweekday=MO, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1998, 12, 28, 9, 0), datetime.datetime(2004, 12, 27, 9, 0), datetime.datetime(2009, 12, 28, 9, 0)] Every Friday the 13th, 4 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, count=4, byweekday=FR, bymonthday=13, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1998, 2, 13, 9, 0), datetime.datetime(1998, 3, 13, 9, 0), datetime.datetime(1998, 11, 13, 9, 0), datetime.datetime(1999, 8, 13, 9, 0)] Every four years, the first Tuesday after a Monday in November, 3 occurrences (U.S. Presidential Election day): .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(YEARLY, interval=4, count=3, bymonth=11, ... byweekday=TU, bymonthday=(2,3,4,5,6,7,8), ... dtstart=parse("19961105T090000"))) [datetime.datetime(1996, 11, 5, 9, 0), datetime.datetime(2000, 11, 7, 9, 0), datetime.datetime(2004, 11, 2, 9, 0)] The 3rd instance into the month of one of Tuesday, Wednesday or Thursday, for the next 3 months: .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=3, byweekday=(TU,WE,TH), ... bysetpos=3, dtstart=parse("19970904T090000"))) [datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 10, 7, 9, 0), datetime.datetime(1997, 11, 6, 9, 0)] The 2nd to last weekday of the month, 3 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MONTHLY, count=3, byweekday=(MO,TU,WE,TH,FR), ... bysetpos=-2, dtstart=parse("19970929T090000"))) [datetime.datetime(1997, 9, 29, 9, 0), datetime.datetime(1997, 10, 30, 9, 0), datetime.datetime(1997, 11, 27, 9, 0)] Every 3 hours from 9:00 AM to 5:00 PM on a specific day. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(HOURLY, interval=3, ... dtstart=parse("19970902T090000"), ... until=parse("19970902T170000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 12, 0), datetime.datetime(1997, 9, 2, 15, 0)] Every 15 minutes for 6 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MINUTELY, interval=15, count=6, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 9, 15), datetime.datetime(1997, 9, 2, 9, 30), datetime.datetime(1997, 9, 2, 9, 45), datetime.datetime(1997, 9, 2, 10, 0), datetime.datetime(1997, 9, 2, 10, 15)] Every hour and a half for 4 occurrences. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(MINUTELY, interval=90, count=4, ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 10, 30), datetime.datetime(1997, 9, 2, 12, 0), datetime.datetime(1997, 9, 2, 13, 30)] Every 20 minutes from 9:00 AM to 4:40 PM for two days. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE, +ELLIPSIS >>> list(rrule(MINUTELY, interval=20, count=48, ... byhour=range(9,17), byminute=(0,20,40), ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 2, 9, 20), ... datetime.datetime(1997, 9, 2, 16, 20), datetime.datetime(1997, 9, 2, 16, 40), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 3, 9, 20), ... datetime.datetime(1997, 9, 3, 16, 20), datetime.datetime(1997, 9, 3, 16, 40)] An example where the days generated makes a difference because of `wkst`. .. doctest:: rrule :options: +NORMALIZE_WHITESPACE >>> list(rrule(WEEKLY, interval=2, count=4, ... byweekday=(TU,SU), wkst=MO, ... dtstart=parse("19970805T090000"))) [datetime.datetime(1997, 8, 5, 9, 0), datetime.datetime(1997, 8, 10, 9, 0), datetime.datetime(1997, 8, 19, 9, 0), datetime.datetime(1997, 8, 24, 9, 0)] >>> list(rrule(WEEKLY, interval=2, count=4, ... byweekday=(TU,SU), wkst=SU, ... dtstart=parse("19970805T090000"))) [datetime.datetime(1997, 8, 5, 9, 0), datetime.datetime(1997, 8, 17, 9, 0), datetime.datetime(1997, 8, 19, 9, 0), datetime.datetime(1997, 8, 31, 9, 0)] rruleset examples ----------------- Daily, for 7 days, jumping Saturday and Sunday occurrences. .. testsetup:: rruleset import datetime from dateutil.parser import parse from dateutil.rrule import rrule, rruleset from dateutil.rrule import YEARLY, MONTHLY, WEEKLY, DAILY from dateutil.rrule import MO, TU, WE, TH, FR, SA, SU import pprint import sys sys.displayhook = pprint.pprint .. doctest:: rruleset :options: +NORMALIZE_WHITESPACE >>> set = rruleset() >>> set.rrule(rrule(DAILY, count=7, ... dtstart=parse("19970902T090000"))) >>> set.exrule(rrule(YEARLY, byweekday=(SA,SU), ... dtstart=parse("19970902T090000"))) >>> list(set) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 3, 9, 0), datetime.datetime(1997, 9, 4, 9, 0), datetime.datetime(1997, 9, 5, 9, 0), datetime.datetime(1997, 9, 8, 9, 0)] Weekly, for 4 weeks, plus one time on day 7, and not on day 16. .. doctest:: rruleset :options: +NORMALIZE_WHITESPACE >>> set = rruleset() >>> set.rrule(rrule(WEEKLY, count=4, ... dtstart=parse("19970902T090000"))) >>> set.rdate(datetime.datetime(1997, 9, 7, 9, 0)) >>> set.exdate(datetime.datetime(1997, 9, 16, 9, 0)) >>> list(set) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 7, 9, 0), datetime.datetime(1997, 9, 9, 9, 0), datetime.datetime(1997, 9, 23, 9, 0)] rrulestr() examples ------------------- Every 10 days, 5 occurrences. .. testsetup:: rrulestr from dateutil.parser import parse from dateutil.rrule import rruleset, rrulestr import pprint import sys sys.displayhook = pprint.pprint .. doctest:: rrulestr :options: +NORMALIZE_WHITESPACE >>> list(rrulestr(""" ... DTSTART:19970902T090000 ... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5 ... """)) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)] Same thing, but passing only the `RRULE` value. .. doctest:: rrulestr :options: +NORMALIZE_WHITESPACE >>> list(rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5", ... dtstart=parse("19970902T090000"))) [datetime.datetime(1997, 9, 2, 9, 0), datetime.datetime(1997, 9, 12, 9, 0), datetime.datetime(1997, 9, 22, 9, 0), datetime.datetime(1997, 10, 2, 9, 0), datetime.datetime(1997, 10, 12, 9, 0)] Notice that when using a single rule, it returns an `rrule` instance, unless `forceset` was used. .. doctest:: rrulestr :options: +ELLIPSIS >>> rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5") >>> rrulestr(""" ... DTSTART:19970902T090000 ... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5 ... """) >>> rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5", forceset=True) But when an `rruleset` is needed, it is automatically used. .. doctest:: rrulestr :options: +ELLIPSIS >>> rrulestr(""" ... DTSTART:19970902T090000 ... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5 ... RRULE:FREQ=DAILY;INTERVAL=5;COUNT=3 ... """) python_dateutil-4.0.0/docs/tz.rst0000644000000000000000000000471613615410400013776 0ustar00== tz == .. py:currentmodule:: dateutil.tz .. automodule:: dateutil.tz Objects ------- .. py:data:: dateutil.tz.UTC A convenience instance of :class:`dateutil.tz.tzutc`. .. versionadded:: 2.7.0 .. py:data:: dateutil.tz.TZPATH A tuple containing the search path for IANA time zone data files. This can be set by the ``PYTHONTZPATH`` environment variable, or updated via :func:`reset_tzpath`. This is an alias for :py:data:`zoneinfo.TZPATH`. .. versionadded:: 3.0.0 Functions --------- .. autofunction:: gettz .. automethod:: gettz.nocache .. automethod:: gettz.cache_clear .. autofunction:: available_iana_timezones .. py:function:: reset_tzpath(to=None) Sets the value of :data:`TZPATH`. This is an alias for :py:func:`zoneinfo.reset_tzpath`, and calling it *will* reset the search path for both ``dateutil`` and :py:mod:`zoneinfo`. :param to: A sequence of absolute paths to search for zoneinfo files. If ``None`` (default), the search path is reset to the default search path, which is determined by the ``PYTHONTZPATH`` environment variable, or a set of platform-specific defaults. .. versionadded:: 3.0.0 .. autofunction:: enfold .. autofunction:: datetime_ambiguous .. autofunction:: datetime_exists .. autofunction:: resolve_imaginary Classes ------- .. autoclass:: tzutc .. autoclass:: tzoffset .. autoclass:: tzlocal .. autoclass:: tzwinlocal :members: display, transitions .. note:: Only available on Windows .. autoclass:: tzrange .. autoclass:: tzstr .. autoclass:: tzical :members: .. autoclass:: tzwin :members: display, transitions, list .. note:: Only available on Windows Warnings -------- .. autoclass:: DeprecatedTzKeyWarning IANA Time Zone Data ------------------- ``dateutil`` attempts to search for time zone data the same way that the standard library does. :data:`TZPATH` is a proxy for :py:data:`zoneinfo.TZPATH` and :py:func:`reset_tzpath` is an alias for :py:func:`zoneinfo.reset_tzpath`. The environment variable ``PYTHONTZPATH`` can be used to configure the search path, as described in the :py:mod:`zoneinfo` documentation. ``dateutil`` also takes an unconditional dependency on the `tzdata `_ package, which provides a self-contained, up-to-date source of IANA time zone data for Python. This data source is only used if no system time zone information is found on the search path. python_dateutil-4.0.0/docs/tzwin.rst0000644000000000000000000000047013615410400014505 0ustar00====== tz.win ====== .. py:currentmodule:: dateutil.tz.win .. automodule:: dateutil.tz.win Classes ------- .. autoclass:: tzres :members: .. autoclass:: tzwin :members: list, display, transitions :undoc-members: .. autoclass:: tzwinlocal :members: display, transitions :undoc-members: python_dateutil-4.0.0/docs/utils.rst0000644000000000000000000000012113615410400014463 0ustar00===== utils ===== .. automodule:: dateutil.utils :members: :undoc-members: python_dateutil-4.0.0/docs/zoneinfo.rst0000644000000000000000000000027113615410400015160 0ustar00======== zoneinfo ======== .. automodule:: dateutil.zoneinfo :members: :undoc-members: .. automodule:: dateutil.zoneinfo.rebuild :members: rebuild, RebuildDeprecationWarning python_dateutil-4.0.0/docs/exercises/index.rst0000644000000000000000000001711713615410400016441 0ustar00Exercises ========= It is often useful to work through some examples in order to understand how a module works; on this page, there are several exercises of varying difficulty that you can use to learn how to use ``dateutil``. If you are interested in helping improve the documentation of ``dateutil``, it is recommended that you attempt to complete these exercises with no resources *other than dateutil's documentation*. If you find that the documentation is not clear enough to allow you to complete these exercises, open an issue on the `dateutil issue tracker `_ to let the developers know what part of the documentation needs improvement. .. contents:: Table of Contents :backlinks: top :local: .. _mlk-day-exercise: Martin Luther King Day -------------------------------- `Martin Luther King, Jr Day `_ is a US holiday that occurs every year on the third Monday in January? How would you generate a :doc:`recurrence rule <../rrule>` that generates Martin Luther King Day, starting from its first observance in 1986? **Test Script** To solve this exercise, copy-paste this script into a document, change anything between the ``--- YOUR CODE ---`` comment blocks. .. raw:: html
.. code-block:: python3 # ------- YOUR CODE -------------# from dateutil import rrule MLK_DAY = <> # -------------------------------# from datetime import datetime MLK_TEST_CASES = [ ((datetime(1970, 1, 1), datetime(1980, 1, 1)), []), ((datetime(1980, 1, 1), datetime(1989, 1, 1)), [datetime(1986, 1, 20), datetime(1987, 1, 19), datetime(1988, 1, 18)]), ((datetime(2017, 2, 1), datetime(2022, 2, 1)), [datetime(2018, 1, 15, 0, 0), datetime(2019, 1, 21, 0, 0), datetime(2020, 1, 20, 0, 0), datetime(2021, 1, 18, 0, 0), datetime(2022, 1, 17, 0, 0)] ), ] def test_mlk_day(): for (between_args, expected) in MLK_TEST_CASES: assert MLK_DAY.between(*between_args) == expected if __name__ == "__main__": test_mlk_day() print('Success!') .. raw:: html
A solution to this problem is provided :doc:`here `. Next Monday meeting ------------------- A team has a meeting at 10 AM every Monday and wants a function that tells them, given a ``datetime.datetime`` object, what is the date and time of the *next* Monday meeting? This is probably best accomplished using a :doc:`relativedelta <../relativedelta>`. **Test Script** To solve this exercise, copy-paste this script into a document, change anything between the ``--- YOUR CODE ---`` comment blocks. .. raw:: html
.. code-block:: python3 # --------- YOUR CODE -------------- # from dateutil import relativedelta def next_monday(dt): <> # ---------------------------------- # from datetime import datetime from dateutil import tz NEXT_MONDAY_CASES = [ (datetime(2018, 4, 11, 14, 30, 15, 123456), datetime(2018, 4, 16, 10, 0)), (datetime(2018, 4, 16, 10, 0), datetime(2018, 4, 16, 10, 0)), (datetime(2018, 4, 16, 10, 30), datetime(2018, 4, 23, 10, 0)), (datetime(2018, 4, 14, 9, 30, tzinfo=tz.gettz('America/New_York')), datetime(2018, 4, 16, 10, 0, tzinfo=tz.gettz('America/New_York'))), ] def test_next_monday_1(): for dt_in, dt_out in NEXT_MONDAY_CASES: assert next_monday(dt_in) == dt_out if __name__ == "__main__": test_next_monday_1() print('Success!') .. raw:: html
Parsing a local tzname ---------------------- Three-character time zone abbreviations are *not* unique in that they do not explicitly map to a time zone. A list of time zone abbreviations in use can be found `here `_. This means that parsing a datetime string such as ``'2018-01-01 12:30:30 CST'`` is ambiguous without context. Using :mod:`dateutil.parser` and :mod:`dateutil.tz`, it is possible to provide a context such that these local names are converted to proper time zones. Problem 1 ********* Given the context that you will only be parsing dates coming from the continental United States, India and Japan, write a function that parses a datetime string and returns a timezone-aware ``datetime`` with an IANA-style timezone attached. Note: For the purposes of the experiment, you may ignore the portions of the United States like Arizona and parts of Indiana that do not observe daylight saving time. **Test Script** To solve this exercise, copy-paste this script into a document, change anything between the ``--- YOUR CODE ---`` comment blocks. .. raw:: html
.. code-block:: python3 # --------- YOUR CODE -------------- # from dateutil.parser import parse from dateutil import tz def parse_func_us_jp_ind(): <> # ---------------------------------- # from dateutil import tz from datetime import datetime PARSE_TZ_TEST_DATETIMES = [ datetime(2018, 1, 1, 12, 0), datetime(2018, 3, 20, 2, 0), datetime(2018, 5, 12, 3, 30), datetime(2014, 9, 1, 23) ] PARSE_TZ_TEST_ZONES = [ tz.gettz('America/New_York'), tz.gettz('America/Chicago'), tz.gettz('America/Denver'), tz.gettz('America/Los_Angeles'), tz.gettz('Asia/Kolkata'), tz.gettz('Asia/Tokyo'), ] def test_parse(): for tzi in PARSE_TZ_TEST_ZONES: for dt in PARSE_TZ_TEST_DATETIMES: dt_exp = dt.replace(tzinfo=tzi) dtstr = dt_exp.strftime('%Y-%m-%d %H:%M:%S %Z') dt_act = parse_func_us_jp_ind(dtstr) assert dt_act == dt_exp assert dt_act.tzinfo is dt_exp.tzinfo if __name__ == "__main__": test_parse() print('Success!') .. raw:: html
Problem 2 ********* Given the context that you will *only* be passed dates from India or Ireland, write a function that correctly parses all *unambiguous* time zone strings to aware datetimes localized to the correct IANA zone, and for *ambiguous* time zone strings default to India. **Test Script** To solve this exercise, copy-paste this script into a document, change anything between the ``--- YOUR CODE ---`` comment blocks. .. raw:: html
.. code-block:: python3 # --------- YOUR CODE -------------- # from dateutil.parser import parse from dateutil import tz def parse_func_ind_ire(): <> # ---------------------------------- # ISRAEL = tz.gettz('Asia/Jerusalem') INDIA = tz.gettz('Asia/Kolkata') PARSE_IXT_TEST_CASE = [ ('2018-02-03 12:00 IST+02:00', datetime(2018, 2, 3, 12, tzinfo=ISRAEL)), ('2018-06-14 12:00 IDT+03:00', datetime(2018, 6, 14, 12, tzinfo=ISRAEL)), ('2018-06-14 12:00 IST', datetime(2018, 6, 14, 12, tzinfo=INDIA)), ('2018-06-14 12:00 IST+05:30', datetime(2018, 6, 14, 12, tzinfo=INDIA)), ('2018-02-03 12:00 IST', datetime(2018, 2, 3, 12, tzinfo=INDIA)), ] def test_parse_ixt(): for dtstr, dt_exp in PARSE_IXT_TEST_CASE: dt_act = parse_func_ind_ire(dtstr) assert dt_act == dt_exp, (dt_act, dt_exp) assert dt_act.tzinfo is dt_exp.tzinfo, (dt_act, dt_exp) if __name__ == "__main__": test_parse_ixt() print('Success!') .. raw:: html
python_dateutil-4.0.0/docs/exercises/solutions/mlk-day-rrule.rst0000644000000000000000000000035113615410400022046 0ustar00:orphan: Martin Luther King Day: Solution ================================ Presented here is a solution to the :ref:`Martin Luther King Day exercises `. .. include:: mlk_day_rrule_solution.py :code: python3 python_dateutil-4.0.0/docs/exercises/solutions/mlk_day_rrule_solution.py0000644000000000000000000000207013615410400023766 0ustar00# ------- YOUR CODE -------------# from dateutil import rrule from datetime import datetime MLK_DAY = rrule.rrule( dtstart=datetime(1986, 1, 20), # First celebration freq=rrule.YEARLY, # Occurs once per year bymonth=1, # In January byweekday=rrule.MO(+3), # On the 3rd Monday ) # -------------------------------# from datetime import datetime MLK_TEST_CASES = [ ((datetime(1970, 1, 1), datetime(1980, 1, 1)), []), ((datetime(1980, 1, 1), datetime(1989, 1, 1)), [datetime(1986, 1, 20), datetime(1987, 1, 19), datetime(1988, 1, 18)]), ((datetime(2017, 2, 1), datetime(2022, 2, 1)), [datetime(2018, 1, 15, 0, 0), datetime(2019, 1, 21, 0, 0), datetime(2020, 1, 20, 0, 0), datetime(2021, 1, 18, 0, 0), datetime(2022, 1, 17, 0, 0)] ), ] def test_mlk_day(): for (between_args, expected) in MLK_TEST_CASES: assert MLK_DAY.between(*between_args) == expected if __name__ == "__main__": test_mlk_day() print('Success!') python_dateutil-4.0.0/docs/samples/EST5EDT.ics0000644000000000000000000000062013615410400016016 0ustar00BEGIN:VTIMEZONE TZID:US-Eastern LAST-MODIFIED:19870101T000000Z TZURL:http://zones.stds_r_us.net/tz/US-Eastern BEGIN:STANDARD DTSTART:19671029T020000 RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 TZNAME:EST END:STANDARD BEGIN:DAYLIGHT DTSTART:19870405T020000 RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 TZNAME:EDT END:DAYLIGHT END:VTIMEZONE python_dateutil-4.0.0/src/dateutil/__init__.py0000644000000000000000000000116213615410400016362 0ustar00import sys try: from ._version import version as __version__ except ImportError: __version__ = 'unknown' __all__ = ["easter", "parser", "relativedelta", "rrule", "tz", "utils"] def __getattr__(name): import importlib if name in __all__ or name == "zoneinfo": return importlib.import_module("." + name, __name__) raise AttributeError( "module {!r} has no attribute {!r}".format(__name__, name) ) def __dir__(): # __dir__ should include all the lazy-importable modules as well. return ( [x for x in globals() if x not in sys.modules] + __all__ + ["zoneinfo"] ) python_dateutil-4.0.0/src/dateutil/_common.py0000644000000000000000000000153313615410400016254 0ustar00""" Common code used in multiple modules. """ class weekday: __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __hash__(self): return hash(( self.weekday, self.n, )) def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) # vim:ts=4:sw=4:et python_dateutil-4.0.0/src/dateutil/_tzdata_impl.py0000644000000000000000000000513613615410400017277 0ustar00"""This is an implementation of functions that interact with the tzdata module. It will only live as long as :mod:`dateutil.zoneinfo` lives; when the ``dateutil.zoneinfo`` module is removed, this can all move under :mod:`tz`. """ import importlib.resources from typing import BinaryIO, TextIO _TZDATA_LOAD_EXCEPTIONS = ( ImportError, FileNotFoundError, UnicodeEncodeError, IsADirectoryError, ValueError, ) def _open_text(package: str, resource: str) -> TextIO: return ( importlib.resources.files(package) .joinpath(resource) .open("r", encoding="utf-8") ) def _open_binary(package: str, resource: str) -> BinaryIO: return importlib.resources.files(package).joinpath(resource).open("rb") def _is_package_directory(package: str, resource: str) -> bool: """Checks for directories before opening resources on Windows.""" try: return importlib.resources.files(package).joinpath(resource).is_dir() except ImportError: return False def _load_tzdata(key): components = key.split("/") package_name = ".".join(["tzdata.zoneinfo"] + components[:-1]) resource_name = components[-1] # Empty or relative path components cannot name a zone, and they produce # module names that the import machinery handles inconsistently across # versions, so treat them as not found up front. A key naming a directory # (a subpackage) is not a zone either, and opening it raises a # platform-dependent error, see CPython gh-85702. if any(c in ("", ".", "..") for c in components) or _is_package_directory( package_name, resource_name ): raise TZFileNotFound("Time zone not found: %s", zone_key=key) try: return _open_binary(package_name, resource_name) except _TZDATA_LOAD_EXCEPTIONS: # ImportError: package does not exist (or tzdata is not installed) # FileNotFoundError: the key is not a file in the package # UnicodeEncodeError: the key is not encodable as a filename # IsADirectoryError: the key names a package rather than a resource # ValueError: the key is not a valid path (e.g. contains a NUL byte) raise TZFileNotFound("Time zone not found: %s", zone_key=key) from None def _load_tzdata_keys(): with _open_text("tzdata", "zones") as f: return list(filter(None, (l.strip() for l in f))) class TZFileNotFound(ValueError): """Indicates that a time zone file isn't present in tzdata.""" def __init__(self, msg: str, *args: object, zone_key: str) -> None: super().__init__(msg % zone_key, *args) self.zone_key = zone_key python_dateutil-4.0.0/src/dateutil/_version.py0000644000000000000000000000101013615410400016437 0ustar00# file generated by vcs-versioning # don't change, don't track in version control from __future__ import annotations __all__ = [ "__version__", "__version_tuple__", "version", "version_tuple", "__commit_id__", "commit_id", ] version: str __version__: str __version_tuple__: tuple[int | str, ...] version_tuple: tuple[int | str, ...] commit_id: str | None __commit_id__: str | None __version__ = version = '4.0.0' __version_tuple__ = version_tuple = (4, 0, 0) __commit_id__ = commit_id = None python_dateutil-4.0.0/src/dateutil/easter.py0000644000000000000000000000513613615410400016113 0ustar00""" This module offers a generic Easter computing method for any given year, using Western, Orthodox or Julian algorithms. """ import datetime __all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 def easter(year, method=EASTER_WESTERN): """ This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This algorithm implements three different Easter calculation methods: 1. Original calculation in Julian calendar, valid in dates after 326 AD 2. Original method, with date converted to Gregorian calendar, valid in years 1583 to 4099 3. Revised method, in Gregorian calendar, valid in years 1583 to 4099 as well These methods are represented by the constants: * ``EASTER_JULIAN = 1`` * ``EASTER_ORTHODOX = 2`` * ``EASTER_WESTERN = 3`` The default method is method 3. More about the algorithm may be found at: `GM Arts: Easter Algorithms `_ and `The Calendar FAQ: Easter `_ """ if not (1 <= method <= 3): raise ValueError("invalid method") # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc) # p - Number of days from March 21 to Sunday on or before PFM # (-6 to 28 methods 1 & 3, to 56 for method 2) # e - Extra days to add for method 2 (converting Julian # date to Gregorian date) y = year g = y % 19 e = 0 if method < 3: # Old method i = (19*g + 15) % 30 j = (y + y//4 + i) % 7 if method == 2: # Extra dates to convert Julian to Gregorian date e = 10 if y > 1600: e = e + y//100 - 16 - (y//100 - 16)//4 else: # New method c = y//100 h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30 i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11)) j = (y + y//4 + i + 2 - c + c//4) % 7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later dates apply to method 2, although 23 May never actually occurs) p = i - j + e d = 1 + (p + 27 + (p + 6)//40) % 31 m = 3 + (p + 26)//30 return datetime.date(int(y), int(m), int(d)) python_dateutil-4.0.0/src/dateutil/relativedelta.py0000644000000000000000000006060213615410400017454 0ustar00import datetime import calendar import operator from math import copysign from warnings import warn from ._common import weekday MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) __all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] class relativedelta: """ The relativedelta type is designed to be applied to an existing datetime and can replace specific components of that datetime, or represents an interval of time. It is based on the specification of the excellent work done by M.-A. Lemburg in his `mx.DateTime `_ extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There are two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:: relativedelta(datetime1, datetime2) The second one is passing it any number of the following keyword arguments:: relativedelta(arg1=x,arg2=y,arg3=z...) year, month, day, hour, minute, second, microsecond: Absolute information (argument is singular); adding or subtracting a relativedelta with absolute information does not perform an arithmetic operation, but rather REPLACES the corresponding value in the original datetime with the value(s) in relativedelta. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative (argument is plural); adding or subtracting a relativedelta with relative information performs the corresponding arithmetic operation on the original datetime value with the information in the relativedelta. weekday: One of the weekday instances (MO, TU, etc) available in the relativedelta module. These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2)). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. This argument is always relative e.g. if the calculated date is already Monday, using MO(1) or MO(-1) won't change the day. To effectively make it absolute, use it in combination with the day argument (e.g. day=1, MO(1) for first Monday of the month). leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. There are relative and absolute forms of the keyword arguments. The plural is relative, and the singular is absolute. For each argument in the order below, the absolute form is applied first (by setting each attribute to that value) and then the relative form (by adding the value to the attribute). The order of attributes considered when this relativedelta is added to a datetime is: 1. Year 2. Month 3. Day 4. Hours 5. Minutes 6. Seconds 7. Microseconds Finally, weekday is applied, using the rule described above. For example >>> from datetime import datetime >>> from dateutil.relativedelta import relativedelta, MO >>> dt = datetime(2018, 4, 9, 13, 37, 0) >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) >>> dt + delta datetime.datetime(2018, 4, 2, 14, 37) First, the day is set to 1 (the first of the month), then 25 hours are added, to get to the 2nd day and 14th hour, finally the weekday is applied, but since the 2nd is already a Monday there is no effect. """ def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): if dt1 and dt2: # datetime is a subclass of date. So both must be date if not (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date)): raise TypeError("relativedelta only diffs datetime/date") # We allow two dates, or two datetimes, so we coerce them to be # of the same type if (isinstance(dt1, datetime.datetime) != isinstance(dt2, datetime.datetime)): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 # Get year / month delta between the two months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) self._set_months(months) # Remove the year/month delta so the timedelta is just well-defined # time units (seconds, days and microseconds) dtm = self.__radd__(dt2) # If we've overshot our target, make an adjustment if dt1 < dt2: compare = operator.gt increment = 1 else: compare = operator.lt increment = -1 while compare(dt1, dtm): months += increment self._set_months(months) dtm = self.__radd__(dt2) # Get the timedelta between the "months-adjusted" date and dt1 delta = dt1 - dtm self.seconds = delta.seconds + delta.days * 86400 self.microseconds = delta.microseconds else: # Check for non-integer values in integer-only quantities if any(x is not None and x != int(x) for x in (years, months)): raise ValueError("Non-integer years and months are " "ambiguous and not currently supported.") # Relative information self.years = int(years) self.months = int(months) self.days = days + weeks * 7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds # Absolute information self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if any(x is not None and int(x) != x for x in (year, month, day, hour, minute, second, microsecond)): # For now we'll deprecate floats - later it'll be an error. warn("Non-integer value passed as absolute information. " + "This is not a well-defined condition and will raise " + "errors in future versions.", DeprecationWarning) if isinstance(weekday, int): self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday # Days after February are converted as common-year days, # and leapdays=-1 moves them back over Feb 29 in leap # years. Day 366 becomes December 32, which is clamped to # December 31, so it must not be moved back. if 59 < yearday < 366: self.leapdays = -1 if yday: ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError("invalid year day (%d)" % yday) self._fix() def _fix(self): if abs(self.microseconds) > 999999: s = _sign(self.microseconds) div, mod = divmod(self.microseconds * s, 1000000) self.microseconds = mod * s self.seconds += div * s if abs(self.seconds) > 59: s = _sign(self.seconds) div, mod = divmod(self.seconds * s, 60) self.seconds = mod * s self.minutes += div * s if abs(self.minutes) > 59: s = _sign(self.minutes) div, mod = divmod(self.minutes * s, 60) self.minutes = mod * s self.hours += div * s if abs(self.hours) > 23: s = _sign(self.hours) div, mod = divmod(self.hours * s, 24) self.hours = mod * s self.days += div * s if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years += div * s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0 @property def weeks(self): return int(self.days / 7.0) @weeks.setter def weeks(self, value): self.days = self.days - (self.weeks * 7) + value * 7 def _set_months(self, months): self.months = months if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years = div * s else: self.years = 0 def normalized(self): """ Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=+1, hours=+14) :return: Returns a :class:`dateutil.relativedelta.relativedelta` object. """ # Cascade remainders down (rounding each to roughly nearest microsecond) days = int(self.days) hours_f = round(self.hours + 24 * (self.days - days), 11) hours = int(hours_f) minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) minutes = int(minutes_f) seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) seconds = int(seconds_f) microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) # Constructor carries overflow back up with call to _fix() return self.__class__(years=self.years, months=self.months, days=days, hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __add__(self, other): if isinstance(other, relativedelta): return self.__class__(years=other.years + self.years, months=other.months + self.months, days=other.days + self.days, hours=other.hours + self.hours, minutes=other.minutes + self.minutes, seconds=other.seconds + self.seconds, microseconds=(other.microseconds + self.microseconds), leapdays=other.leapdays or self.leapdays, year=(other.year if other.year is not None else self.year), month=(other.month if other.month is not None else self.month), day=(other.day if other.day is not None else self.day), weekday=(other.weekday if other.weekday is not None else self.weekday), hour=(other.hour if other.hour is not None else self.hour), minute=(other.minute if other.minute is not None else self.minute), second=(other.second if other.second is not None else self.second), microsecond=(other.microsecond if other.microsecond is not None else self.microsecond)) if isinstance(other, datetime.timedelta): return self.__class__(years=self.years, months=self.months, days=self.days + other.days, hours=self.hours, minutes=self.minutes, seconds=self.seconds + other.seconds, microseconds=self.microseconds + other.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) if not isinstance(other, datetime.date): return NotImplemented elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth) - 1) * 7 if nth > 0: jumpdays += (7 - ret.weekday() + weekday) % 7 else: jumpdays += (ret.weekday() - weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return self.__neg__().__radd__(other) def __sub__(self, other): if not isinstance(other, relativedelta): return NotImplemented # In case the other object defines __rsub__ return self.__class__(years=self.years - other.years, months=self.months - other.months, days=self.days - other.days, hours=self.hours - other.hours, minutes=self.minutes - other.minutes, seconds=self.seconds - other.seconds, microseconds=self.microseconds - other.microseconds, leapdays=self.leapdays or other.leapdays, year=(self.year if self.year is not None else other.year), month=(self.month if self.month is not None else other.month), day=(self.day if self.day is not None else other.day), weekday=(self.weekday if self.weekday is not None else other.weekday), hour=(self.hour if self.hour is not None else other.hour), minute=(self.minute if self.minute is not None else other.minute), second=(self.second if self.second is not None else other.second), microsecond=(self.microsecond if self.microsecond is not None else other.microsecond)) def __abs__(self): return self.__class__(years=abs(self.years), months=abs(self.months), days=abs(self.days), hours=abs(self.hours), minutes=abs(self.minutes), seconds=abs(self.seconds), microseconds=abs(self.microseconds), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __neg__(self): return self.__class__(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __bool__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None) def __mul__(self, other): try: f = float(other) except TypeError: return NotImplemented return self.__class__(years=int(self.years * f), months=int(self.months * f), days=int(self.days * f), hours=int(self.hours * f), minutes=int(self.minutes * f), seconds=int(self.seconds * f), microseconds=int(self.microseconds * f), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) __rmul__ = __mul__ def __eq__(self, other): if not isinstance(other, relativedelta): return NotImplemented if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.microseconds == other.microseconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond) def __hash__(self): return hash(( self.weekday, self.years, self.months, self.days, self.hours, self.minutes, self.seconds, self.microseconds, self.leapdays, self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond, )) def __truediv__(self, other): try: reciprocal = 1 / float(other) except TypeError: return NotImplemented return self.__mul__(reciprocal) def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("{attr}={value:+g}".format(attr=attr, value=value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("{attr}={value}".format(attr=attr, value=repr(value))) return "{classname}({attrs})".format(classname=self.__class__.__name__, attrs=", ".join(l)) def _sign(x): return int(copysign(1, x)) # vim:ts=4:sw=4:et python_dateutil-4.0.0/src/dateutil/rrule.py0000644000000000000000000020301013615410400015750 0ustar00""" The rrule module offers a small, complete, and very fast, implementation of the recurrence rules documented in the `iCalendar RFC `_, including support for caching of results. """ import _thread import calendar import datetime import heapq import itertools import math import re import sys from functools import wraps # For warning about deprecation of until and count from warnings import warn from ._common import weekday as weekdaybase __all__ = ["rrule", "rruleset", "rrulestr", "YEARLY", "MONTHLY", "WEEKLY", "DAILY", "HOURLY", "MINUTELY", "SECONDLY", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] # Every mask is 7 days longer to handle cross-year weekly periods. M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 + [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) M365MASK = list(M366MASK) M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32)) MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) MDAY365MASK = list(MDAY366MASK) M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0)) NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) NMDAY365MASK = list(NMDAY366MASK) M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55 del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] MDAY365MASK = tuple(MDAY365MASK) M365MASK = tuple(M365MASK) FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY'] (YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY) = list(range(7)) # Imported on demand. easter = None parser = None class weekday(weekdaybase): """ This version of weekday does not allow n = 0. """ def __init__(self, wkday, n=None): if n == 0: raise ValueError("Can't create weekday with n==0") super().__init__(wkday, n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) def _invalidates_cache(f): """ Decorator for rruleset methods which may invalidate the cached length. """ @wraps(f) def inner_func(self, *args, **kwargs): rv = f(self, *args, **kwargs) self._invalidate_cache() return rv return inner_func class rrulebase: def __init__(self, cache=False): if cache: self._cache = [] self._cache_lock = _thread.allocate_lock() self._invalidate_cache() else: self._cache = None self._cache_complete = False self._len = None def __reduce_ex__(self, protocol): rv = super().__reduce_ex__(protocol) state, slots = rv[2], None if isinstance(state, tuple): state, slots = state if self._cache is not None: state = dict(state) state.pop("_cache_lock", None) state.pop("_cache_gen", None) state["_cache"] = [] if slots is not None: state = (state, slots) return rv[:2] + (state,) + rv[3:] def __setstate__(self, state): if isinstance(state, tuple): state, slots = state for name, value in slots.items(): setattr(self, name, value) self.__dict__.update(state) if self._cache is not None: self._cache_lock = _thread.allocate_lock() self._invalidate_cache() def __iter__(self): if self._cache_complete: return iter(self._cache) elif self._cache is None: return self._iter() else: return self._iter_cached() def _invalidate_cache(self): if self._cache is not None: self._cache = [] self._cache_complete = False self._cache_gen = self._iter() if self._cache_lock.locked(): self._cache_lock.release() self._len = None def _iter_cached(self): i = 0 gen = self._cache_gen cache = self._cache lock = self._cache_lock while gen: if i == len(cache): with lock: if self._cache_complete: break try: for j in range(10): cache.append(next(gen)) except StopIteration: self._cache_gen = gen = None self._cache_complete = True break yield cache[i] i += 1 while i < self._len: yield cache[i] i += 1 def __getitem__(self, item): if self._cache_complete: return self._cache[item] elif isinstance(item, slice): if item.step and item.step < 0: return list(iter(self))[item] else: return list(itertools.islice(self, item.start or 0, item.stop or sys.maxsize, item.step or 1)) elif item >= 0: gen = iter(self) try: for i in range(item+1): res = next(gen) except StopIteration: raise IndexError return res else: return list(iter(self))[item] def __contains__(self, item): if self._cache_complete: return item in self._cache else: for i in self: if i == item: return True elif i > item: return False return False # __len__() introduces a large performance penalty. def count(self): """ Returns the number of recurrences in this set. It will have go through the whole recurrence, if this hasn't been done before. """ if self._len is None: for x in self: pass return self._len def before(self, dt, inc=False): """ Returns the last recurrence before the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc=True, if dt itself is an occurrence, it will be returned. """ if self._cache_complete: gen = self._cache else: gen = self last = None if inc: for i in gen: if i > dt: break last = i else: for i in gen: if i >= dt: break last = i return last def after(self, dt, inc=False): """ Returns the first recurrence after the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc=True, if dt itself is an occurrence, it will be returned. """ if self._cache_complete: gen = self._cache else: gen = self if inc: for i in gen: if i >= dt: return i else: for i in gen: if i > dt: return i return None def xafter(self, dt, count=None, inc=False): """ Generator which yields up to `count` recurrences after the given datetime instance, equivalent to `after`. :param dt: The datetime at which to start generating recurrences. :param count: The maximum number of recurrences to generate. If `None` (default), dates are generated until the recurrence rule is exhausted. :param inc: If `dt` is an instance of the rule and `inc` is `True`, it is included in the output. :yields: Yields a sequence of `datetime` objects. """ if self._cache_complete: gen = self._cache else: gen = self # Select the comparison function if inc: comp = lambda dc, dtc: dc >= dtc else: comp = lambda dc, dtc: dc > dtc # Generate dates n = 0 for d in gen: if comp(d, dt): if count is not None: n += 1 if n > count: break yield d def between(self, after, before, inc=False, count=1): """ Returns all the occurrences of the rrule between after and before. The inc keyword defines what happens if after and/or before are themselves occurrences. With inc=True, they will be included in the list, if they are found in the recurrence set. """ if self._cache_complete: gen = self._cache else: gen = self started = False l = [] if inc: for i in gen: if i > before: break elif not started: if i >= after: started = True l.append(i) else: l.append(i) else: for i in gen: if i >= before: break elif not started: if i > after: started = True l.append(i) else: l.append(i) return l class rrule(rrulebase): """ That's the base of the rrule operation. It accepts all the keywords defined in the RFC as its constructor parameters (except byday, which was renamed to byweekday) and more. The constructor prototype is:: rrule(freq) Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. .. note:: Per RFC section 3.3.10, recurrence instances falling on invalid dates and times are ignored rather than coerced: Recurrence rules may generate recurrence instances with an invalid date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM on a day where the local time is moved forward by an hour at 1:00 AM). Such recurrence instances MUST be ignored and MUST NOT be counted as part of the recurrence set. This can lead to possibly surprising behavior when, for example, the start date occurs at the end of the month: >>> from dateutil.rrule import rrule, MONTHLY >>> from datetime import datetime >>> start_date = datetime(2014, 12, 31) >>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date)) ... # doctest: +NORMALIZE_WHITESPACE [datetime.datetime(2014, 12, 31, 0, 0), datetime.datetime(2015, 1, 31, 0, 0), datetime.datetime(2015, 3, 31, 0, 0), datetime.datetime(2015, 5, 31, 0, 0)] Additionally, it supports the following keyword arguments: :param dtstart: The recurrence start. Besides being the base for the recurrence, missing parameters in the final recurrence instances will also be extracted from this date. If not given, datetime.now() will be used instead. :param interval: The interval between each freq iteration. For example, when using YEARLY, an interval of 2 means once every two years, but with HOURLY, it means once every two hours. The default interval is 1. :param wkst: The week start day. Must be one of the MO, TU, WE constants, or an integer, specifying the first day of the week. This will affect recurrences based on weekly periods. The default week start is got from calendar.firstweekday(), and may be modified by calendar.setfirstweekday(). :param count: If given, this determines how many occurrences will be generated. .. note:: As of version 2.5.0, the use of the keyword ``until`` in conjunction with ``count`` is deprecated, to make sure ``dateutil`` is fully compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` **must not** occur in the same call to ``rrule``. :param until: If given, this must be a datetime instance specifying the upper-bound limit of the recurrence. The last recurrence in the rule is the greatest datetime that is less than or equal to the value specified in the ``until`` parameter. .. note:: As of version 2.5.0, the use of the keyword ``until`` in conjunction with ``count`` is deprecated, to make sure ``dateutil`` is fully compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` **must not** occur in the same call to ``rrule``. :param bysetpos: If given, it must be either an integer, or a sequence of integers, positive or negative. Each given integer will specify an occurrence number, corresponding to the nth occurrence of the rule inside the frequency period. For example, a bysetpos of -1 if combined with a MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will result in the last work day of every month. :param bymonth: If given, it must be either an integer, or a sequence of integers, meaning the months to apply the recurrence to. :param bymonthday: If given, it must be either an integer, or a sequence of integers, meaning the month days to apply the recurrence to. :param byyearday: If given, it must be either an integer, or a sequence of integers, meaning the year days to apply the recurrence to. :param byeaster: If given, it must be either an integer, or a sequence of integers, positive or negative. Each integer will define an offset from the Easter Sunday. Passing the offset 0 to byeaster will yield the Easter Sunday itself. This is an extension to the RFC specification. :param byweekno: If given, it must be either an integer, or a sequence of integers, meaning the week numbers to apply the recurrence to. Week numbers have the meaning described in ISO8601, that is, the first week of the year is that containing at least four days of the new year. :param byweekday: If given, it must be either an integer (0 == MO), a sequence of integers, one of the weekday constants (MO, TU, etc), or a sequence of these constants. When given, these variables will define the weekdays where the recurrence will be applied. It's also possible to use an argument n for the weekday instances, which will mean the nth occurrence of this weekday in the period. For example, with MONTHLY, or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the first friday of the month where the recurrence happens. Notice that in the RFC documentation, this is specified as BYDAY, but was renamed to avoid the ambiguity of that keyword. :param byhour: If given, it must be either an integer, or a sequence of integers, meaning the hours to apply the recurrence to. :param byminute: If given, it must be either an integer, or a sequence of integers, meaning the minutes to apply the recurrence to. :param bysecond: If given, it must be either an integer, or a sequence of integers, meaning the seconds to apply the recurrence to. :param cache: If given, it must be a boolean value specifying to enable or disable caching of results. If you will use the same rrule instance multiple times, enabling caching will improve the performance considerably. """ def __init__(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False): super().__init__(cache) global easter if not dtstart: if until and until.tzinfo: dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0) else: dtstart = datetime.datetime.now().replace(microsecond=0) elif not isinstance(dtstart, datetime.datetime): dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) else: dtstart = dtstart.replace(microsecond=0) self._dtstart = dtstart self._tzinfo = dtstart.tzinfo self._freq = freq self._interval = interval self._count = count # Cache the original byxxx rules, if they are provided, as the _byxxx # attributes do not necessarily map to the inputs, and this can be # a problem in generating the strings. Only store things if they've # been supplied (the string retrieval will just use .get()) self._original_rule = {} if until and not isinstance(until, datetime.datetime): until = datetime.datetime.fromordinal(until.toordinal()) self._until = until if self._dtstart and self._until: if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None): # According to RFC5545 Section 3.3.10: # https://tools.ietf.org/html/rfc5545#section-3.3.10 # # > If the "DTSTART" property is specified as a date with UTC # > time or a date with local time and time zone reference, # > then the UNTIL rule part MUST be specified as a date with # > UTC time. raise ValueError( 'RRULE UNTIL values must be specified in UTC when DTSTART ' 'is timezone-aware' ) if count is not None and until: warn("Using both 'count' and 'until' is inconsistent with RFC 5545" " and has been deprecated in dateutil. Future versions will " "raise an error.", DeprecationWarning) if wkst is None: self._wkst = calendar.firstweekday() elif isinstance(wkst, int): self._wkst = wkst else: self._wkst = wkst.weekday if bysetpos is None: self._bysetpos = None elif isinstance(bysetpos, int): if bysetpos == 0 or not (-366 <= bysetpos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") self._bysetpos = (bysetpos,) else: self._bysetpos = tuple(bysetpos) for pos in self._bysetpos: if pos == 0 or not (-366 <= pos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") if self._bysetpos: self._original_rule['bysetpos'] = self._bysetpos if (byweekno is None and byyearday is None and bymonthday is None and byweekday is None and byeaster is None): if freq == YEARLY: if bymonth is None: bymonth = dtstart.month self._original_rule['bymonth'] = None bymonthday = dtstart.day self._original_rule['bymonthday'] = None elif freq == MONTHLY: bymonthday = dtstart.day self._original_rule['bymonthday'] = None elif freq == WEEKLY: byweekday = dtstart.weekday() self._original_rule['byweekday'] = None # bymonth if bymonth is None: self._bymonth = None else: if isinstance(bymonth, int): bymonth = (bymonth,) self._bymonth = tuple(sorted(set(bymonth))) if 'bymonth' not in self._original_rule: self._original_rule['bymonth'] = self._bymonth # byyearday if byyearday is None: self._byyearday = None else: if isinstance(byyearday, int): byyearday = (byyearday,) self._byyearday = tuple(sorted(set(byyearday))) self._original_rule['byyearday'] = self._byyearday # byeaster if byeaster is not None: if not easter: from dateutil import easter if isinstance(byeaster, int): self._byeaster = (byeaster,) else: self._byeaster = tuple(sorted(byeaster)) self._original_rule['byeaster'] = self._byeaster else: self._byeaster = None # bymonthday if bymonthday is None: self._bymonthday = () self._bynmonthday = () else: if isinstance(bymonthday, int): bymonthday = (bymonthday,) bymonthday = set(bymonthday) # Ensure it's unique self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0)) self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0)) # Storing positive numbers first, then negative numbers if 'bymonthday' not in self._original_rule: self._original_rule['bymonthday'] = tuple( itertools.chain(self._bymonthday, self._bynmonthday)) # byweekno if byweekno is None: self._byweekno = None else: if isinstance(byweekno, int): byweekno = (byweekno,) self._byweekno = tuple(sorted(set(byweekno))) self._original_rule['byweekno'] = self._byweekno # byweekday / bynweekday if byweekday is None: self._byweekday = None self._bynweekday = None else: # If it's one of the valid non-sequence types, convert to a # single-element sequence before the iterator that builds the # byweekday set. if isinstance(byweekday, int) or hasattr(byweekday, "n"): byweekday = (byweekday,) self._byweekday = set() self._bynweekday = set() for wday in byweekday: if isinstance(wday, int): self._byweekday.add(wday) elif not wday.n or freq > MONTHLY: self._byweekday.add(wday.weekday) else: self._bynweekday.add((wday.weekday, wday.n)) if not self._byweekday: self._byweekday = None elif not self._bynweekday: self._bynweekday = None if self._byweekday is not None: self._byweekday = tuple(sorted(self._byweekday)) orig_byweekday = [weekday(x) for x in self._byweekday] else: orig_byweekday = () if self._bynweekday is not None: self._bynweekday = tuple(sorted(self._bynweekday)) orig_bynweekday = [weekday(*x) for x in self._bynweekday] else: orig_bynweekday = () if 'byweekday' not in self._original_rule: self._original_rule['byweekday'] = tuple(itertools.chain( orig_byweekday, orig_bynweekday)) # byhour if byhour is None: if freq < HOURLY: self._byhour = {dtstart.hour} else: self._byhour = None else: if isinstance(byhour, int): byhour = (byhour,) if freq == HOURLY: self._byhour = self.__construct_byset(start=dtstart.hour, byxxx=byhour, base=24) else: self._byhour = set(byhour) self._byhour = tuple(sorted(self._byhour)) self._original_rule['byhour'] = self._byhour # byminute if byminute is None: if freq < MINUTELY: self._byminute = {dtstart.minute} else: self._byminute = None else: if isinstance(byminute, int): byminute = (byminute,) if freq == MINUTELY: self._byminute = self.__construct_byset(start=dtstart.minute, byxxx=byminute, base=60) else: self._byminute = set(byminute) self._byminute = tuple(sorted(self._byminute)) self._original_rule['byminute'] = self._byminute # bysecond if bysecond is None: if freq < SECONDLY: self._bysecond = ((dtstart.second,)) else: self._bysecond = None else: if isinstance(bysecond, int): bysecond = (bysecond,) self._bysecond = set(bysecond) if freq == SECONDLY: self._bysecond = self.__construct_byset(start=dtstart.second, byxxx=bysecond, base=60) else: self._bysecond = set(bysecond) self._bysecond = tuple(sorted(self._bysecond)) self._original_rule['bysecond'] = self._bysecond if self._freq >= HOURLY: self._timeset = None else: self._timeset = [] for hour in self._byhour: for minute in self._byminute: for second in self._bysecond: self._timeset.append( datetime.time(hour, minute, second, tzinfo=self._tzinfo)) self._timeset.sort() self._timeset = tuple(self._timeset) def __str__(self): """ Output a string that would generate this RRULE if passed to rrulestr. This is mostly compatible with RFC5545, except for the dateutil-specific extension BYEASTER. """ output = [] h, m, s = [None] * 3 if self._dtstart: output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S')) h, m, s = self._dtstart.timetuple()[3:6] parts = ['FREQ=' + FREQNAMES[self._freq]] if self._interval != 1: parts.append('INTERVAL=' + str(self._interval)) if self._wkst: parts.append('WKST=' + repr(weekday(self._wkst))[0:2]) if self._count is not None: parts.append('COUNT=' + str(self._count)) if self._until: parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S')) if self._original_rule.get('byweekday') is not None: # The str() method on weekday objects doesn't generate # RFC5545-compliant strings, so we should modify that. original_rule = dict(self._original_rule) wday_strings = [] for wday in original_rule['byweekday']: if wday.n: wday_strings.append('{n:+d}{wday}'.format( n=wday.n, wday=repr(wday)[0:2])) else: wday_strings.append(repr(wday)) original_rule['byweekday'] = wday_strings else: original_rule = self._original_rule partfmt = '{name}={vals}' for name, key in [('BYSETPOS', 'bysetpos'), ('BYMONTH', 'bymonth'), ('BYMONTHDAY', 'bymonthday'), ('BYYEARDAY', 'byyearday'), ('BYWEEKNO', 'byweekno'), ('BYDAY', 'byweekday'), ('BYHOUR', 'byhour'), ('BYMINUTE', 'byminute'), ('BYSECOND', 'bysecond'), ('BYEASTER', 'byeaster')]: value = original_rule.get(key) if value: parts.append(partfmt.format(name=name, vals=(','.join(str(v) for v in value)))) output.append('RRULE:' + ';'.join(parts)) return '\n'.join(output) def replace(self, **kwargs): """Return new rrule with same attributes except for those attributes given new values by whichever keyword arguments are specified.""" new_kwargs = {"interval": self._interval, "count": self._count, "dtstart": self._dtstart, "freq": self._freq, "until": self._until, "wkst": self._wkst, "cache": False if self._cache is None else True } new_kwargs.update(self._original_rule) new_kwargs.update(kwargs) return rrule(**new_kwargs) def _iter(self): year, month, day, hour, minute, second, weekday, yearday, _ = \ self._dtstart.timetuple() # Some local variables to speed things up a bit freq = self._freq interval = self._interval wkst = self._wkst until = self._until bymonth = self._bymonth byweekno = self._byweekno byyearday = self._byyearday byweekday = self._byweekday byeaster = self._byeaster bymonthday = self._bymonthday bynmonthday = self._bynmonthday bysetpos = self._bysetpos byhour = self._byhour byminute = self._byminute bysecond = self._bysecond ii = _iterinfo(self) ii.rebuild(year, month) getdayset = {YEARLY: ii.ydayset, MONTHLY: ii.mdayset, WEEKLY: ii.wdayset, DAILY: ii.ddayset, HOURLY: ii.ddayset, MINUTELY: ii.ddayset, SECONDLY: ii.ddayset}[freq] if freq < HOURLY: timeset = self._timeset else: gettimeset = {HOURLY: ii.htimeset, MINUTELY: ii.mtimeset, SECONDLY: ii.stimeset}[freq] if ((freq >= HOURLY and self._byhour and hour not in self._byhour) or (freq >= MINUTELY and self._byminute and minute not in self._byminute) or (freq >= SECONDLY and self._bysecond and second not in self._bysecond)): timeset = () else: timeset = gettimeset(hour, minute, second) total = 0 count = self._count while True: # Get dayset with the right frequency dayset, start, end = getdayset(year, month, day) # Do the "hard" work ;-) filtered = False for i in dayset[start:end]: if ((bymonth and ii.mmask[i] not in bymonth) or (byweekno and not ii.wnomask[i]) or (byweekday and ii.wdaymask[i] not in byweekday) or (ii.nwdaymask and not ii.nwdaymask[i]) or (byeaster and not ii.eastermask[i]) or ((bymonthday or bynmonthday) and ii.mdaymask[i] not in bymonthday and ii.nmdaymask[i] not in bynmonthday) or (byyearday and ((i < ii.yearlen and i+1 not in byyearday and -ii.yearlen+i not in byyearday) or (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and -ii.nextyearlen+i-ii.yearlen not in byyearday)))): dayset[i] = None filtered = True # Output results if bysetpos and timeset: poslist = [] for pos in bysetpos: if pos < 0: daypos, timepos = divmod(pos, len(timeset)) else: daypos, timepos = divmod(pos-1, len(timeset)) try: i = [x for x in dayset[start:end] if x is not None][daypos] time = timeset[timepos] except IndexError: pass else: date = datetime.date.fromordinal(ii.yearordinal+i) res = datetime.datetime.combine(date, time) if res not in poslist: poslist.append(res) poslist.sort() for res in poslist: if until and res > until: self._len = total return elif res >= self._dtstart: if count is not None: count -= 1 if count < 0: self._len = total return total += 1 yield res else: for i in dayset[start:end]: if i is not None: date = datetime.date.fromordinal(ii.yearordinal + i) for time in timeset: res = datetime.datetime.combine(date, time) if until and res > until: self._len = total return elif res >= self._dtstart: if count is not None: count -= 1 if count < 0: self._len = total return total += 1 yield res # Handle frequency and interval fixday = False if freq == YEARLY: year += interval if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == MONTHLY: month += interval if month > 12: div, mod = divmod(month, 12) month = mod year += div if month == 0: month = 12 year -= 1 if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == WEEKLY: if wkst > weekday: day += -(weekday+1+(6-wkst))+self._interval*7 else: day += -(weekday-wkst)+self._interval*7 weekday = wkst fixday = True elif freq == DAILY: day += interval fixday = True elif freq == HOURLY: if filtered: # Jump to one iteration before next day hour += ((23-hour)//interval)*interval if byhour: ndays, hour = self.__mod_distance(value=hour, byxxx=self._byhour, base=24) else: ndays, hour = divmod(hour+interval, 24) if ndays: day += ndays fixday = True timeset = gettimeset(hour, minute, second) elif freq == MINUTELY: if filtered: # Jump to one iteration before next day minute += ((1439-(hour*60+minute))//interval)*interval valid = False rep_rate = (24*60) for j in range(rep_rate // math.gcd(interval, rep_rate)): if byminute: nhours, minute = \ self.__mod_distance(value=minute, byxxx=self._byminute, base=60) else: nhours, minute = divmod(minute+interval, 60) div, hour = divmod(hour+nhours, 24) if div: day += div fixday = True filtered = False if not byhour or hour in byhour: valid = True break if not valid: raise ValueError('Invalid combination of interval and ' + 'byhour resulting in empty rule.') timeset = gettimeset(hour, minute, second) elif freq == SECONDLY: if filtered: # Jump to one iteration before next day second += (((86399 - (hour * 3600 + minute * 60 + second)) // interval) * interval) rep_rate = (24 * 3600) valid = False for j in range(0, rep_rate // math.gcd(interval, rep_rate)): if bysecond: nminutes, second = \ self.__mod_distance(value=second, byxxx=self._bysecond, base=60) else: nminutes, second = divmod(second+interval, 60) div, minute = divmod(minute+nminutes, 60) if div: hour += div div, hour = divmod(hour, 24) if div: day += div fixday = True if ((not byhour or hour in byhour) and (not byminute or minute in byminute) and (not bysecond or second in bysecond)): valid = True break if not valid: raise ValueError('Invalid combination of interval, ' + 'byhour and byminute resulting in empty' + ' rule.') timeset = gettimeset(hour, minute, second) if fixday and day > 28: daysinmonth = calendar.monthrange(year, month)[1] if day > daysinmonth: while day > daysinmonth: day -= daysinmonth month += 1 if month == 13: month = 1 year += 1 if year > datetime.MAXYEAR: self._len = total return daysinmonth = calendar.monthrange(year, month)[1] ii.rebuild(year, month) def __construct_byset(self, start, byxxx, base): """ If a `BYXXX` sequence is passed to the constructor at the same level as `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some specifications which cannot be reached given some starting conditions. This occurs whenever the interval is not coprime with the base of a given unit and the difference between the starting position and the ending position is not coprime with the greatest common denominator between the interval and the base. For example, with a FREQ of hourly starting at 17:00 and an interval of 4, the only valid values for BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not coprime. :param start: Specifies the starting position. :param byxxx: An iterable containing the list of allowed values. :param base: The largest allowable value for the specified frequency (e.g. 24 hours, 60 minutes). This does not preserve the type of the iterable, returning a set, since the values should be unique and the order is irrelevant, this will speed up later lookups. In the event of an empty set, raises a :exception:`ValueError`, as this results in an empty rrule. """ cset = set() # Support a single byxxx value. if isinstance(byxxx, int): byxxx = (byxxx, ) for num in byxxx: i_gcd = math.gcd(self._interval, base) # Use divmod rather than % because we need to wrap negative nums. if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0: cset.add(num) if len(cset) == 0: raise ValueError("Invalid rrule byxxx generates an empty set.") return cset def __mod_distance(self, value, byxxx, base): """ Calculates the next value in a sequence where the `FREQ` parameter is specified along with a `BYXXX` parameter at the same "level" (e.g. `HOURLY` specified with `BYHOUR`). :param value: The old value of the component. :param byxxx: The `BYXXX` set, which should have been generated by `rrule._construct_byset`, or something else which checks that a valid rule is present. :param base: The largest allowable value for the specified frequency (e.g. 24 hours, 60 minutes). If a valid value is not found after `base` iterations (the maximum number before the sequence would start to repeat), this raises a :exception:`ValueError`, as no valid values were found. This returns a tuple of `divmod(n*interval, base)`, where `n` is the smallest number of `interval` repetitions until the next specified value in `byxxx` is found. """ accumulator = 0 for ii in range(1, base + 1): # Using divmod() over % to account for negative intervals div, value = divmod(value + self._interval, base) accumulator += div if value in byxxx: return (accumulator, value) class _iterinfo: __slots__ = ["rrule", "lastyear", "lastmonth", "yearlen", "nextyearlen", "yearordinal", "yearweekday", "mmask", "mrange", "mdaymask", "nmdaymask", "wdaymask", "wnomask", "nwdaymask", "eastermask"] def __init__(self, rrule): for attr in self.__slots__: setattr(self, attr, None) self.rrule = rrule def rebuild(self, year, month): # Every mask is 7 days longer to handle cross-year weekly periods. rr = self.rrule if year != self.lastyear: self.yearlen = 365 + calendar.isleap(year) self.nextyearlen = 365 + calendar.isleap(year + 1) firstyday = datetime.date(year, 1, 1) self.yearordinal = firstyday.toordinal() self.yearweekday = firstyday.weekday() wday = datetime.date(year, 1, 1).weekday() if self.yearlen == 365: self.mmask = M365MASK self.mdaymask = MDAY365MASK self.nmdaymask = NMDAY365MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M365RANGE else: self.mmask = M366MASK self.mdaymask = MDAY366MASK self.nmdaymask = NMDAY366MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M366RANGE if not rr._byweekno: self.wnomask = None else: self.wnomask = [0]*(self.yearlen+7) # no1wkst = firstwkst = self.wdaymask.index(rr._wkst) no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7 if no1wkst >= 4: no1wkst = 0 # Number of days in the year, plus the days we got # from last year. wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7 else: # Number of days in the year, minus the days we # left in last year. wyearlen = self.yearlen-no1wkst div, mod = divmod(wyearlen, 7) numweeks = div+mod//4 for n in rr._byweekno: if n < 0: n += numweeks+1 if not (0 < n <= numweeks): continue if n > 1: i = no1wkst+(n-1)*7 if no1wkst != firstwkst: i -= 7-firstwkst else: i = no1wkst for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if 1 in rr._byweekno: # Check week number 1 of next year as well # TODO: Check -numweeks for next year. i = no1wkst+numweeks*7 if no1wkst != firstwkst: i -= 7-firstwkst if i < self.yearlen: # If week starts in next year, we # don't care about it. for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if no1wkst: # Check last week number of last year as # well. If no1wkst is 0, either the year # started on week start, or week number 1 # got days from last year, so there are no # days from last year's last week number in # this year. if -1 not in rr._byweekno: lyearweekday = datetime.date(year-1, 1, 1).weekday() lno1wkst = (7-lyearweekday+rr._wkst) % 7 lyearlen = 365+calendar.isleap(year-1) if lno1wkst >= 4: lno1wkst = 0 lnumweeks = 52+(lyearlen + (lyearweekday-rr._wkst) % 7) % 7//4 else: lnumweeks = 52+(self.yearlen-no1wkst) % 7//4 else: lnumweeks = -1 if lnumweeks in rr._byweekno: for i in range(no1wkst): self.wnomask[i] = 1 if (rr._bynweekday and (month != self.lastmonth or year != self.lastyear)): ranges = [] if rr._freq == YEARLY: if rr._bymonth: for month in rr._bymonth: ranges.append(self.mrange[month-1:month+1]) else: ranges = [(0, self.yearlen)] elif rr._freq == MONTHLY: ranges = [self.mrange[month-1:month+1]] if ranges: # Weekly frequency won't get here, so we may not # care about cross-year weekly periods. self.nwdaymask = [0]*self.yearlen for first, last in ranges: last -= 1 for wday, n in rr._bynweekday: if n < 0: i = last+(n+1)*7 i -= (self.wdaymask[i]-wday) % 7 else: i = first+(n-1)*7 i += (7-self.wdaymask[i]+wday) % 7 if first <= i <= last: self.nwdaymask[i] = 1 if rr._byeaster: self.eastermask = [0]*(self.yearlen+7) eyday = easter.easter(year).toordinal()-self.yearordinal for offset in rr._byeaster: self.eastermask[eyday+offset] = 1 self.lastyear = year self.lastmonth = month def ydayset(self, year, month, day): return list(range(self.yearlen)), 0, self.yearlen def mdayset(self, year, month, day): dset = [None]*self.yearlen start, end = self.mrange[month-1:month+1] for i in range(start, end): dset[i] = i return dset, start, end def wdayset(self, year, month, day): # We need to handle cross-year weeks here. dset = [None]*(self.yearlen+7) i = datetime.date(year, month, day).toordinal()-self.yearordinal start = i for j in range(7): dset[i] = i i += 1 # if (not (0 <= i < self.yearlen) or # self.wdaymask[i] == self.rrule._wkst): # This will cross the year boundary, if necessary. if self.wdaymask[i] == self.rrule._wkst: break return dset, start, i def ddayset(self, year, month, day): dset = [None] * self.yearlen i = datetime.date(year, month, day).toordinal() - self.yearordinal dset[i] = i return dset, i, i + 1 def htimeset(self, hour, minute, second): tset = [] rr = self.rrule for minute in rr._byminute: for second in rr._bysecond: tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) tset.sort() return tset def mtimeset(self, hour, minute, second): tset = [] rr = self.rrule for second in rr._bysecond: tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) tset.sort() return tset def stimeset(self, hour, minute, second): return (datetime.time(hour, minute, second, tzinfo=self.rrule._tzinfo),) class rruleset(rrulebase): """ The rruleset type allows more complex recurrence setups, mixing multiple rules, dates, exclusion rules, and exclusion dates. The type constructor takes the following keyword arguments: :param cache: If True, caching of results will be enabled, improving performance of multiple queries considerably. """ class _genitem: def __init__(self, genlist, gen): try: self.dt = next(gen) genlist.append(self) except StopIteration: pass self.genlist = genlist self.gen = gen def __next__(self): try: self.dt = next(self.gen) except StopIteration: if self.genlist[0] is self: heapq.heappop(self.genlist) else: self.genlist.remove(self) heapq.heapify(self.genlist) def __lt__(self, other): return self.dt < other.dt def __gt__(self, other): return self.dt > other.dt def __eq__(self, other): return self.dt == other.dt def __ne__(self, other): return self.dt != other.dt def __init__(self, cache=False): super().__init__(cache) self._rrule = [] self._rdate = [] self._exrule = [] self._exdate = [] @_invalidates_cache def rrule(self, rrule): """ Include the given :py:class:`rrule` instance in the recurrence set generation. """ self._rrule.append(rrule) @_invalidates_cache def rdate(self, rdate): """ Include the given :py:class:`datetime` instance in the recurrence set generation. """ self._rdate.append(rdate) @_invalidates_cache def exrule(self, exrule): """ Include the given rrule instance in the recurrence set exclusion list. Dates which are part of the given recurrence rules will not be generated, even if some inclusive rrule or rdate matches them. """ self._exrule.append(exrule) @_invalidates_cache def exdate(self, exdate): """ Include the given datetime instance in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them. """ self._exdate.append(exdate) def _iter(self): rlist = [] self._rdate.sort() self._genitem(rlist, iter(self._rdate)) for gen in [iter(x) for x in self._rrule]: self._genitem(rlist, gen) exlist = [] self._exdate.sort() self._genitem(exlist, iter(self._exdate)) for gen in [iter(x) for x in self._exrule]: self._genitem(exlist, gen) lastdt = None total = 0 heapq.heapify(rlist) heapq.heapify(exlist) while rlist: ritem = rlist[0] if not lastdt or lastdt != ritem.dt: while exlist and exlist[0] < ritem: exitem = exlist[0] next(exitem) if exlist and exlist[0] is exitem: heapq.heapreplace(exlist, exitem) if not exlist or ritem != exlist[0]: total += 1 yield ritem.dt lastdt = ritem.dt next(ritem) if rlist and rlist[0] is ritem: heapq.heapreplace(rlist, ritem) self._len = total class _rrulestr: """ Parses a string representation of a recurrence rule or set of recurrence rules. :param s: Required, a string defining one or more recurrence rules. :param dtstart: If given, used as the default recurrence start if not specified in the rule string. :param cache: If set ``True`` caching of results will be enabled, improving performance of multiple queries considerably. :param unfold: If set ``True`` indicates that a rule string is split over more than one line and should be joined before processing. :param forceset: If set ``True`` forces a :class:`dateutil.rrule.rruleset` to be returned. :param compatible: If set ``True`` forces ``unfold`` and ``forceset`` to be ``True``. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime.datetime` object is returned. :param tzids: If given, a callable or mapping used to retrieve a :class:`datetime.tzinfo` from a string representation. Defaults to :func:`dateutil.tz.gettz`. :param tzinfos: Additional time zone names / aliases which may be present in a string representation. See :func:`dateutil.parser.parse` for more information. :return: Returns a :class:`dateutil.rrule.rruleset` or :class:`dateutil.rrule.rrule` """ _freq_map = {"YEARLY": YEARLY, "MONTHLY": MONTHLY, "WEEKLY": WEEKLY, "DAILY": DAILY, "HOURLY": HOURLY, "MINUTELY": MINUTELY, "SECONDLY": SECONDLY} _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3, "FR": 4, "SA": 5, "SU": 6} def _handle_int(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = int(value) def _handle_int_list(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = [int(x) for x in value.split(',')] _handle_INTERVAL = _handle_int _handle_COUNT = _handle_int _handle_BYSETPOS = _handle_int_list _handle_BYMONTH = _handle_int_list _handle_BYMONTHDAY = _handle_int_list _handle_BYYEARDAY = _handle_int_list _handle_BYEASTER = _handle_int_list _handle_BYWEEKNO = _handle_int_list _handle_BYHOUR = _handle_int_list _handle_BYMINUTE = _handle_int_list _handle_BYSECOND = _handle_int_list def _handle_FREQ(self, rrkwargs, name, value, **kwargs): rrkwargs["freq"] = self._freq_map[value] def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): global parser if not parser: from dateutil import parser try: rrkwargs["until"] = parser.parse(value, ignoretz=kwargs.get("ignoretz"), tzinfos=kwargs.get("tzinfos")) except ValueError: raise ValueError("invalid until date") def _handle_WKST(self, rrkwargs, name, value, **kwargs): rrkwargs["wkst"] = self._weekday_map[value] def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs): """ Two ways to specify this: +1MO or MO(+1) """ l = [] for wday in value.split(','): if '(' in wday: # If it's of the form TH(+1), etc. splt = wday.split('(') w = splt[0] n = int(splt[1][:-1]) elif len(wday): # If it's of the form +1MO for i in range(len(wday)): if wday[i] not in '+-0123456789': break n = wday[:i] or None w = wday[i:] if n: n = int(n) else: raise ValueError("Invalid (empty) BYDAY specification.") l.append(weekdays[self._weekday_map[w]](n)) rrkwargs["byweekday"] = l _handle_BYDAY = _handle_BYWEEKDAY def _parse_rfc_rrule(self, line, dtstart=None, cache=False, ignoretz=False, tzinfos=None): if line.find(':') != -1: name, value = line.split(':') if name != "RRULE": raise ValueError("unknown parameter name") else: value = line rrkwargs = {} for pair in value.split(';'): name, value = pair.split('=') name = name.upper() value = value.upper() try: getattr(self, "_handle_"+name)(rrkwargs, name, value, ignoretz=ignoretz, tzinfos=tzinfos) except AttributeError: raise ValueError("unknown parameter '%s'" % name) except (KeyError, ValueError): raise ValueError("invalid '%s': %s" % (name, value)) return rrule(dtstart=dtstart, cache=cache, **rrkwargs) def _parse_date_value(self, date_value, parms, rule_tzids, ignoretz, tzids, tzinfos): global parser if not parser: from dateutil import parser datevals = [] value_found = False TZID = None for parm in parms: if parm.startswith("TZID="): try: tzkey = rule_tzids[parm.split('TZID=')[-1]] except KeyError: continue if tzids is None: from . import tz tzlookup = tz.gettz elif callable(tzids): tzlookup = tzids else: tzlookup = getattr(tzids, 'get', None) if tzlookup is None: msg = ('tzids must be a callable, mapping, or None, ' 'not %s' % tzids) raise ValueError(msg) TZID = tzlookup(tzkey) continue # RFC 5445 3.8.2.4: The VALUE parameter is optional, but may be found # only once. if parm not in {"VALUE=DATE-TIME", "VALUE=DATE"}: raise ValueError("unsupported parm: " + parm) else: if value_found: msg = ("Duplicate value parameter found in: " + parm) raise ValueError(msg) value_found = True for datestr in date_value.split(','): date = parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos) if TZID is not None: if date.tzinfo is None: date = date.replace(tzinfo=TZID) else: raise ValueError('DTSTART/EXDATE specifies multiple timezone') datevals.append(date) return datevals def _parse_rfc(self, s, dtstart=None, cache=False, unfold=False, forceset=False, compatible=False, ignoretz=False, tzids=None, tzinfos=None): global parser if compatible: forceset = True unfold = True TZID_NAMES = dict(map( lambda x: (x.upper(), x), re.findall('TZID=(?P[^:]+):', s) )) s = s.upper() if not s.strip(): raise ValueError("empty string") if unfold: lines = s.splitlines() i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 else: lines = s.split() if (not forceset and len(lines) == 1 and (s.find(':') == -1 or s.startswith('RRULE:'))): return self._parse_rfc_rrule(lines[0], cache=cache, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos) else: rrulevals = [] rdatevals = [] exrulevals = [] exdatevals = [] for line in lines: if not line: continue if line.find(':') == -1: name = "RRULE" value = line else: name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError("empty property name") name = parms[0] parms = parms[1:] if name == "RRULE": for parm in parms: if parm.startswith("X-"): # Experimental random vendor features; safe to ignore continue raise ValueError("unsupported RRULE parm: " + parm) rrulevals.append(value) elif name == "RDATE": for parm in parms: if parm != "VALUE=DATE-TIME": raise ValueError("unsupported RDATE parm: "+parm) rdatevals.append(value) elif name == "EXRULE": for parm in parms: raise ValueError("unsupported EXRULE parm: "+parm) exrulevals.append(value) elif name == "EXDATE": exdatevals.extend( self._parse_date_value(value, parms, TZID_NAMES, ignoretz, tzids, tzinfos) ) elif name == "DTSTART": dtvals = self._parse_date_value(value, parms, TZID_NAMES, ignoretz, tzids, tzinfos) if len(dtvals) != 1: raise ValueError("Multiple DTSTART values specified:" + value) dtstart = dtvals[0] else: raise ValueError("unsupported property: "+name) if (forceset or len(rrulevals) > 1 or rdatevals or exrulevals or exdatevals): if not parser and (rdatevals or exdatevals): from dateutil import parser rset = rruleset(cache=cache) for value in rrulevals: rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in rdatevals: for datestr in value.split(','): rset.rdate(parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exrulevals: rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exdatevals: rset.exdate(value) if compatible and dtstart: rset.rdate(dtstart) return rset else: return self._parse_rfc_rrule(rrulevals[0], dtstart=dtstart, cache=cache, ignoretz=ignoretz, tzinfos=tzinfos) def __call__(self, s, **kwargs): return self._parse_rfc(s, **kwargs) rrulestr = _rrulestr() # vim:ts=4:sw=4:et python_dateutil-4.0.0/src/dateutil/tzwin.py0000644000000000000000000000007313615410400015776 0ustar00# tzwin has moved to dateutil.tz.win from .tz.win import * python_dateutil-4.0.0/src/dateutil/utils.py0000644000000000000000000000355513615410400015773 0ustar00""" This module offers general convenience and utility functions for dealing with datetimes. .. versionadded:: 2.7.0 """ from datetime import datetime, time def today(tzinfo=None): """ Returns a :py:class:`datetime` representing the current day at midnight :param tzinfo: The time zone to attach (also used to determine the current day). :return: A :py:class:`datetime.datetime` object representing the current day at midnight. """ dt = datetime.now(tzinfo) return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) def default_tzinfo(dt, tzinfo): """ Sets the ``tzinfo`` parameter on naive datetimes only This is useful for example when you are provided a datetime that may have either an implicit or explicit time zone, such as when parsing a time zone string. .. doctest:: >>> from dateutil.tz import tzoffset >>> from dateutil.parser import parse >>> from dateutil.utils import default_tzinfo >>> dflt_tz = tzoffset("EST", -18000) >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) 2014-01-01 12:30:00+00:00 >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) 2014-01-01 12:30:00-05:00 :param dt: The datetime on which to replace the time zone :param tzinfo: The :py:class:`datetime.tzinfo` subclass instance to assign to ``dt`` if (and only if) it is naive. :return: Returns an aware :py:class:`datetime.datetime`. """ if dt.tzinfo is not None: return dt else: return dt.replace(tzinfo=tzinfo) def within_delta(dt1, dt2, delta): """ Useful for comparing two datetimes that may have a negligible difference to be considered equal. """ delta = abs(delta) difference = dt1 - dt2 return -delta <= difference <= delta python_dateutil-4.0.0/src/dateutil/parser/__init__.py0000644000000000000000000000321613615410400017660 0ustar00from ._parser import ( DEFAULTPARSER, DEFAULTTZPARSER, ParserError, UnknownTimezoneWarning, __doc__, parse, parser, parserinfo, ) from .isoparser import isoparse, isoparser __all__ = ['parse', 'parser', 'parserinfo', 'isoparse', 'isoparser', 'ParserError', 'UnknownTimezoneWarning'] ### # Deprecate portions of the private interface so that downstream code that # is improperly relying on it is given *some* notice. def __deprecated_private_func(f): import warnings from functools import wraps msg = ('{name} is a private function and may break without warning, ' 'it will be moved and or renamed in future versions.') msg = msg.format(name=f.__name__) @wraps(f) def deprecated_func(*args, **kwargs): warnings.warn(msg, DeprecationWarning) return f(*args, **kwargs) return deprecated_func def __deprecate_private_class(c): import warnings msg = ('{name} is a private class and may break without warning, ' 'it will be moved and or renamed in future versions.') msg = msg.format(name=c.__name__) class private_class(c): __doc__ = c.__doc__ def __init__(self, *args, **kwargs): warnings.warn(msg, DeprecationWarning) super().__init__(*args, **kwargs) private_class.__name__ = c.__name__ return private_class from ._parser import _parsetz, _resultbase, _timelex, _tzparser _timelex = __deprecate_private_class(_timelex) _tzparser = __deprecate_private_class(_tzparser) _resultbase = __deprecate_private_class(_resultbase) _parsetz = __deprecated_private_func(_parsetz) python_dateutil-4.0.0/src/dateutil/parser/_parser.py0000644000000000000000000016214613615410400017564 0ustar00""" This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time. This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous. If an element of a date/time stamp is omitted, the following rules are applied: - If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is specified. - If a time zone is omitted, a timezone-naive datetime is returned. If any other elements are missing, they are taken from the :class:`datetime.datetime` object passed to the parameter ``default``. If this results in a day number exceeding the valid number of days per month, the value falls back to the end of the month. Additional resources about date/time string formats can be found below: - `A summary of the international standard date and time notation `_ - `W3C Date and Time Formats `_ - `Time Formats (Planetary Rings Node) `_ - `CPAN ParseDate module `_ - `Java SimpleDateFormat Class `_ """ import datetime import re import string import time import warnings from calendar import monthrange from io import StringIO from decimal import Decimal from warnings import warn from .. import relativedelta from .. import tz __all__ = ["parse", "parserinfo", "ParserError"] # TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth # making public and/or figuring out if there is something we can # take off their plate. class _timelex: # Fractional seconds are sometimes split by a comma _split_decimal = re.compile("([.,])") def __init__(self, instream): if isinstance(instream, (bytes, bytearray)): instream = instream.decode() if isinstance(instream, str): instream = StringIO(instream) elif getattr(instream, 'read', None) is None: raise TypeError('Parser must be a string or character stream, not ' '{itype}'.format(itype=instream.__class__.__name__)) self.instream = instream self.charstack = [] self.tokenstack = [] self.eof = False def get_token(self): """ This function breaks the time string into lexical units (tokens), which can be parsed by the parser. Lexical units are demarcated by changes in the character set, so any continuous string of letters is considered one unit, any continuous string of numbers is considered one unit. The main complication arises from the fact that dots ('.') can be used both as separators (e.g. "Sep.20.2009") or decimal points (e.g. "4:30:21.447"). As such, it is necessary to read the full context of any dot-separated strings before breaking it into tokens; as such, this function maintains a "token stack", for when the ambiguous context demands that multiple tokens be parsed at once. """ if self.tokenstack: return self.tokenstack.pop(0) seenletters = False token = None state = None while not self.eof: # We only realize that we've reached the end of a token when we # find a character that's not part of the current token - since # that character may be part of the next token, it's stored in the # charstack. if self.charstack: nextchar = self.charstack.pop(0) else: nextchar = self.instream.read(1) while nextchar == '\x00': nextchar = self.instream.read(1) if not nextchar: self.eof = True break elif not state: # First character of the token - determines if we're starting # to parse a word, a number or something else. token = nextchar if self.isword(nextchar): state = 'a' elif self.isnum(nextchar): state = '0' elif self.isspace(nextchar): token = ' ' break # emit token else: break # emit token elif state == 'a': # If we've already started reading a word, we keep reading # letters until we find something that's not part of a word. seenletters = True if self.isword(nextchar): token += nextchar elif nextchar == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token elif state == '0': # If we've already started reading a number, we keep reading # numbers until we find something that doesn't fit. if self.isnum(nextchar): token += nextchar elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == 'a.': # If we've seen some letters and a dot separator, continue # parsing, and the tokens will be broken up later. seenletters = True if nextchar == '.' or self.isword(nextchar): token += nextchar elif self.isnum(nextchar) and token[-1] == '.': token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == '0.': # If we've seen at least one dot separator, keep going, we'll # break up the tokens later. if nextchar == '.' or self.isnum(nextchar): token += nextchar elif self.isword(nextchar) and token[-1] == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or token[-1] in '.,')): l = self._split_decimal.split(token) token = l[0] for tok in l[1:]: if tok: self.tokenstack.append(tok) if state == '0.' and token.count('.') == 0: token = token.replace(',', '.') return token def __iter__(self): return self def __next__(self): token = self.get_token() if token is None: raise StopIteration return token @classmethod def split(cls, s): return list(cls(s)) @classmethod def isword(cls, nextchar): """ Whether or not the next character is part of a word """ return nextchar.isalpha() @classmethod def isnum(cls, nextchar): """ Whether the next character is part of a number """ return nextchar.isdigit() @classmethod def isspace(cls, nextchar): """ Whether the next character is whitespace """ return nextchar.isspace() class _resultbase: def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def _repr(self, classname): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (classname, ", ".join(l)) def __len__(self): return (sum(getattr(self, attr) is not None for attr in self.__slots__)) def __repr__(self): return self._repr(self.__class__.__name__) class parserinfo: """ Class which handles what inputs are accepted. Subclass this to customize the language and acceptable values for each parameter. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. Default is ``False``. :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. Default is ``False``. """ # m from a.m/p.m, t from ISO T separator JUMP = [" ", ".", ",", ";", "-", "/", "'", "at", "on", "and", "ad", "m", "t", "of", "st", "nd", "rd", "th"] WEEKDAYS = [("Mon", "Monday"), ("Tue", "Tuesday"), # TODO: "Tues" ("Wed", "Wednesday"), ("Thu", "Thursday"), # TODO: "Thurs" ("Fri", "Friday"), ("Sat", "Saturday"), ("Sun", "Sunday")] MONTHS = [("Jan", "January"), ("Feb", "February"), # TODO: "Febr" ("Mar", "March"), ("Apr", "April"), ("May", "May"), ("Jun", "June"), ("Jul", "July"), ("Aug", "August"), ("Sep", "Sept", "September"), ("Oct", "October"), ("Nov", "November"), ("Dec", "December")] HMS = [("h", "hour", "hours"), ("m", "minute", "minutes"), ("s", "second", "seconds")] AMPM = [("am", "a"), ("pm", "p")] UTCZONE = ["UTC", "GMT", "Z", "z"] PERTAIN = ["of"] TZOFFSET = {} # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", # "Anno Domini", "Year of Our Lord"] def __init__(self, dayfirst=False, yearfirst=False): self._jump = self._convert(self.JUMP) self._weekdays = self._convert(self.WEEKDAYS) self._months = self._convert(self.MONTHS) self._hms = self._convert(self.HMS) self._ampm = self._convert(self.AMPM) self._utczone = self._convert(self.UTCZONE) self._pertain = self._convert(self.PERTAIN) self.dayfirst = dayfirst self.yearfirst = yearfirst self._year = time.localtime().tm_year self._century = self._year // 100 * 100 def _convert(self, lst): dct = {} for i, v in enumerate(lst): if isinstance(v, tuple): for v in v: dct[v.lower()] = i else: dct[v.lower()] = i return dct def jump(self, name): return name.lower() in self._jump def weekday(self, name): try: return self._weekdays[name.lower()] except KeyError: pass return None def month(self, name): try: return self._months[name.lower()] + 1 except KeyError: pass return None def hms(self, name): try: return self._hms[name.lower()] except KeyError: return None def ampm(self, name): try: return self._ampm[name.lower()] except KeyError: return None def pertain(self, name): return name.lower() in self._pertain def utczone(self, name): return name.lower() in self._utczone def tzoffset(self, name): if name in self._utczone: return 0 return self.TZOFFSET.get(name) def convertyear(self, year, century_specified=False): """ Converts two-digit years to year within [-50, 49] range of self._year (current local time) """ # Function contract is that the year is always positive assert year >= 0 if year < 100 and not century_specified: # assume current century to start year += self._century if year >= self._year + 50: # if too far in future year -= 100 elif year < self._year - 50: # if too far in past year += 100 return year def validate(self, res): # move to info if res.year is not None: res.year = self.convertyear(res.year, res.century_specified) if ((res.tzoffset == 0 and not res.tzname) or (res.tzname == 'Z' or res.tzname == 'z')): res.tzname = "UTC" res.tzoffset = 0 elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): res.tzoffset = 0 return True class _ymd(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.century_specified = False self.dstridx = None self.mstridx = None self.ystridx = None @property def has_year(self): return self.ystridx is not None @property def has_month(self): return self.mstridx is not None @property def has_day(self): return self.dstridx is not None def could_be_day(self, value): if self.has_day: return False elif not self.has_month: return 1 <= value <= 31 elif not self.has_year: # Be permissive, assume leap year month = self[self.mstridx] return 1 <= value <= monthrange(2000, month)[1] else: month = self[self.mstridx] year = self[self.ystridx] return 1 <= value <= monthrange(year, month)[1] def append(self, val, label=None): if hasattr(val, '__len__'): if val.isdigit() and len(val) > 2: self.century_specified = True if label not in [None, 'Y']: # pragma: no cover raise ValueError(label) label = 'Y' elif val > 100: self.century_specified = True if label not in [None, 'Y']: # pragma: no cover raise ValueError(label) label = 'Y' super().append(int(val)) if label == 'M': if self.has_month: raise ValueError('Month is already set') self.mstridx = len(self) - 1 elif label == 'D': if self.has_day: raise ValueError('Day is already set') self.dstridx = len(self) - 1 elif label == 'Y': if self.has_year: raise ValueError('Year is already set') self.ystridx = len(self) - 1 def _resolve_from_stridxs(self, strids): """ Try to resolve the identities of year/month/day elements using ystridx, mstridx, and dstridx, if enough of these are specified. """ if len(self) == 3 and len(strids) == 2: # we can back out the remaining stridx value missing = [x for x in range(3) if x not in strids.values()] key = [x for x in ['y', 'm', 'd'] if x not in strids] assert len(missing) == len(key) == 1 key = key[0] val = missing[0] strids[key] = val assert len(self) == len(strids) # otherwise this should not be called out = {key: self[strids[key]] for key in strids} return (out.get('y'), out.get('m'), out.get('d')) def resolve_ymd(self, yearfirst, dayfirst): len_ymd = len(self) year, month, day = (None, None, None) strids = (('y', self.ystridx), ('m', self.mstridx), ('d', self.dstridx)) strids = {key: val for key, val in strids if val is not None} if (len(self) == len(strids) > 0 or (len(self) == 3 and len(strids) == 2)): return self._resolve_from_stridxs(strids) mstridx = self.mstridx if len_ymd > 3: raise ValueError("More than three YMD values") elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): # One member, or two members with a month string if mstridx is not None: month = self[mstridx] # since mstridx is 0 or 1, self[mstridx-1] always # looks up the other element other = self[mstridx - 1] else: other = self[0] if len_ymd > 1 or mstridx is None: if other > 31: year = other else: day = other elif len_ymd == 2: # Two members with numbers if self[0] > 31: # 99-01 year, month = self elif self[1] > 31: # 01-99 month, year = self elif dayfirst and self[1] <= 12: # 13-01 day, month = self else: # 01-13 month, day = self elif len_ymd == 3: # Three members if mstridx == 0: if self[1] > 31: # Apr-2003-25 month, year, day = self else: month, day, year = self elif mstridx == 1: if self[0] > 31 or (yearfirst and self[2] <= 31): # 99-Jan-01 year, month, day = self else: # 01-Jan-01 # Give precedence to day-first, since # two-digit years is usually hand-written. day, month, year = self elif mstridx == 2: # WTF!? if self[1] > 31: # 01-99-Jan day, year, month = self else: # 99-01-Jan year, day, month = self else: if (self[0] > 31 or self.ystridx == 0 or (yearfirst and self[1] <= 12 and self[2] <= 31)): # 99-01-01 if dayfirst and self[2] <= 12: year, day, month = self else: year, month, day = self elif self[0] > 12 or (dayfirst and self[1] <= 12): # 13-01-01 day, month, year = self else: # 01-13-01 month, day, year = self return year, month, day class parser: def __init__(self, info=None): self.info = info or parserinfo() def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs): """ Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime.datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param \\*\\*kwargs: Keyword arguments as passed to ``_parse()``. :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ParserError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises TypeError: Raised for non-string or character stream input. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. """ if default is None: default = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) res, skipped_tokens = self._parse(timestr, **kwargs) if res is None: raise ParserError("Unknown string format: %s", timestr) if len(res) == 0: raise ParserError("String does not contain a date: %s", timestr) try: ret = self._build_naive(res, default) except ValueError as e: raise ParserError(str(e) + ": %s", timestr) from e if not ignoretz: ret = self._build_tzaware(ret, res, tzinfos) if kwargs.get('fuzzy_with_tokens', False): return ret, skipped_tokens else: return ret class _result(_resultbase): __slots__ = ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond", "tzname", "tzoffset", "ampm","any_unused_tokens"] def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, fuzzy_with_tokens=False): """ Private method which performs the heavy lifting of parsing, called from ``parse()``, which passes on its ``kwargs`` to this function. :param timestr: The string to parse. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. If set to ``None``, this value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to ``None``, the value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param fuzzy: Whether to allow fuzzy parsing, allowing for string like "Today is January 1, 2047 at 8:21:00AM". :param fuzzy_with_tokens: If ``True``, ``fuzzy`` is automatically set to True, and the parser will return a tuple where the first element is the parsed :class:`datetime.datetime` datetimestamp and the second element is a tuple containing the portions of the string which were ignored: .. doctest:: >>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) """ if fuzzy_with_tokens: fuzzy = True info = self.info if dayfirst is None: dayfirst = info.dayfirst if yearfirst is None: yearfirst = info.yearfirst res = self._result() l = _timelex.split(timestr) # Splits the timestr into tokens skipped_idxs = [] # year/month/day list ymd = _ymd() len_l = len(l) i = 0 try: while i < len_l: # Check if it's a number value_repr = l[i] try: value = float(value_repr) except ValueError: value = None if value is not None: # Numeric token i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) # Check weekday elif info.weekday(l[i]) is not None: value = info.weekday(l[i]) res.weekday = value # Check month name elif info.month(l[i]) is not None: value = info.month(l[i]) ymd.append(value, 'M') if i + 1 < len_l: if l[i + 1] in ('-', '/'): # Jan-01[-99] sep = l[i + 1] ymd.append(l[i + 2]) if i + 3 < len_l and l[i + 3] == sep: # Jan-01-99 ymd.append(l[i + 4]) i += 2 i += 2 elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and info.pertain(l[i + 2])): # Jan of 01 # In this case, 01 is clearly year if l[i + 4].isdigit(): # Convert it here to become unambiguous value = int(l[i + 4]) year = str(info.convertyear(value)) ymd.append(year, 'Y') else: # Wrong guess pass # TODO: not hit in tests i += 4 # Check am/pm elif info.ampm(l[i]) is not None: value = info.ampm(l[i]) val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) if val_is_ampm: res.hour = self._adjust_ampm(res.hour, value) res.ampm = value elif fuzzy: skipped_idxs.append(i) # Check for a timezone name elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): res.tzname = l[i] res.tzoffset = info.tzoffset(res.tzname) # Check for something like GMT+3, or BRST+3. Notice # that it doesn't mean "I am 3 hours after GMT", but # "my time +3 is GMT". If found, we reverse the # logic so that timezone parsing code will get it # right. if i + 1 < len_l and l[i + 1] in ('+', '-'): l[i + 1] = ('+', '-')[l[i + 1] == '+'] res.tzoffset = None if info.utczone(res.tzname): # With something like GMT+3, the timezone # is *not* GMT. res.tzname = None # Check for a numbered timezone elif res.hour is not None and l[i] in ('+', '-'): signal = (-1, 1)[l[i] == '+'] len_li = len(l[i + 1]) # TODO: check that l[i + 1] is integer? if len_li == 4: # -0300 hour_offset = int(l[i + 1][:2]) min_offset = int(l[i + 1][2:]) elif i + 2 < len_l and l[i + 2] == ':': # -03:00 hour_offset = int(l[i + 1]) min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? i += 2 elif len_li <= 2: # -[0]3 hour_offset = int(l[i + 1][:2]) min_offset = 0 else: raise ValueError(timestr) res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) # Look for a timezone name between parenthesis if (i + 5 < len_l and info.jump(l[i + 2]) and l[i + 3] == '(' and l[i + 5] == ')' and 3 <= len(l[i + 4]) and self._could_be_tzname(res.hour, res.tzname, None, l[i + 4])): # -0300 (BRST) res.tzname = l[i + 4] i += 4 i += 1 # Check jumps elif not (info.jump(l[i]) or fuzzy): raise ValueError(timestr) else: skipped_idxs.append(i) i += 1 # Process year/month/day year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) res.century_specified = ymd.century_specified res.year = year res.month = month res.day = day except (IndexError, ValueError): return None, None if not info.validate(res): return None, None if fuzzy_with_tokens: skipped_tokens = self._recombine_skipped(l, skipped_idxs) return res, tuple(skipped_tokens) else: return res, None def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): # Token is a number value_repr = tokens[idx] try: value = self._to_decimal(value_repr) except Exception as e: raise ValueError("Unknown numeric token") from e len_li = len(value_repr) len_l = len(tokens) if (len(ymd) == 3 and len_li in (2, 4) and res.hour is None and (idx + 1 >= len_l or (tokens[idx + 1] != ':' and info.hms(tokens[idx + 1]) is None))): # 19990101T23[59] s = tokens[idx] res.hour = int(s[:2]) if len_li == 4: res.minute = int(s[2:]) elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): # YYMMDD or HHMMSS[.ss] s = tokens[idx] if not ymd and '.' not in tokens[idx]: ymd.append(s[:2]) ymd.append(s[2:4]) ymd.append(s[4:]) else: # 19990101T235959[.59] # TODO: Check if res attributes already set. res.hour = int(s[:2]) res.minute = int(s[2:4]) res.second, res.microsecond = self._parsems(s[4:]) elif len_li in (8, 12, 14): # YYYYMMDD s = tokens[idx] ymd.append(s[:4], 'Y') ymd.append(s[4:6]) ymd.append(s[6:8]) if len_li > 8: res.hour = int(s[8:10]) res.minute = int(s[10:12]) if len_li > 12: res.second = int(s[12:]) elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: # HH[ ]h or MM[ ]m or SS[.ss][ ]s hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) if hms is not None: # TODO: checking that hour/minute/second are not # already set? self._assign_hms(res, value_repr, hms) elif idx + 2 < len_l and tokens[idx + 1] == ':': # HH:MM[:SS[.ss]] res.hour = int(value) value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? (res.minute, res.second) = self._parse_min_sec(value) if idx + 4 < len_l and tokens[idx + 3] == ':': res.second, res.microsecond = self._parsems(tokens[idx + 4]) idx += 2 idx += 2 elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): sep = tokens[idx + 1] ymd.append(value_repr) if idx + 2 < len_l and not info.jump(tokens[idx + 2]): if tokens[idx + 2].isdigit(): # 01-01[-01] ymd.append(tokens[idx + 2]) else: # 01-Jan[-01] value = info.month(tokens[idx + 2]) if value is not None: ymd.append(value, 'M') else: raise ValueError() if idx + 3 < len_l and tokens[idx + 3] == sep: # We have three members value = info.month(tokens[idx + 4]) if value is not None: ymd.append(value, 'M') else: ymd.append(tokens[idx + 4]) idx += 2 idx += 1 idx += 1 elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: # 12 am hour = int(value) res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) idx += 1 else: # Year, month or day ymd.append(value) idx += 1 elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): # 12am hour = int(value) res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) idx += 1 elif ymd.could_be_day(value): ymd.append(value) elif not fuzzy: raise ValueError() return idx def _find_hms_idx(self, idx, tokens, info, allow_jump): len_l = len(tokens) if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: # There is an "h", "m", or "s" label following this token. We take # assign the upcoming label to the current token. # e.g. the "12" in 12h" hms_idx = idx + 1 elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and info.hms(tokens[idx+2]) is not None): # There is a space and then an "h", "m", or "s" label. # e.g. the "12" in "12 h" hms_idx = idx + 2 elif idx > 0 and info.hms(tokens[idx-1]) is not None: # There is a "h", "m", or "s" preceding this token. Since neither # of the previous cases was hit, there is no label following this # token, so we use the previous label. # e.g. the "04" in "12h04" hms_idx = idx-1 elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and info.hms(tokens[idx-2]) is not None): # If we are looking at the final token, we allow for a # backward-looking check to skip over a space. # TODO: Are we sure this is the right condition here? hms_idx = idx - 2 else: hms_idx = None return hms_idx def _assign_hms(self, res, value_repr, hms): # See GH issue #427, fixing float rounding value = self._to_decimal(value_repr) if hms == 0: # Hour res.hour = int(value) if value % 1: res.minute = int(60*(value % 1)) elif hms == 1: (res.minute, res.second) = self._parse_min_sec(value) elif hms == 2: (res.second, res.microsecond) = self._parsems(value_repr) def _could_be_tzname(self, hour, tzname, tzoffset, token): return (hour is not None and tzname is None and tzoffset is None and len(token) <= 5 and (all(x in string.ascii_uppercase for x in token) or token in self.info.UTCZONE)) def _ampm_valid(self, hour, ampm, fuzzy): """ For fuzzy parsing, 'a' or 'am' (both valid English words) may erroneously trigger the AM/PM flag. Deal with that here. """ val_is_ampm = True # If there's already an AM/PM flag, this one isn't one. if fuzzy and ampm is not None: val_is_ampm = False # If AM/PM is found and hour is not, raise a ValueError if hour is None: if fuzzy: val_is_ampm = False else: raise ValueError('No hour specified with AM or PM flag.') elif not 0 <= hour <= 12: # If AM/PM is found, it's a 12 hour clock, so raise # an error for invalid range if fuzzy: val_is_ampm = False else: raise ValueError('Invalid hour specified for 12-hour clock.') return val_is_ampm def _adjust_ampm(self, hour, ampm): if hour < 12 and ampm == 1: hour += 12 elif hour == 12 and ampm == 0: hour = 0 return hour def _parse_min_sec(self, value): # TODO: Every usage of this function sets res.second to the return # value. Are there any cases where second will be returned as None and # we *don't* want to set res.second = None? minute = int(value) second = None sec_remainder = value % 1 if sec_remainder: second = int(60 * sec_remainder) return (minute, second) def _parse_hms(self, idx, tokens, info, hms_idx): # TODO: Is this going to admit a lot of false-positives for when we # just happen to have digits and "h", "m" or "s" characters in non-date # text? I guess hex hashes won't have that problem, but there's plenty # of random junk out there. if hms_idx is None: hms = None new_idx = idx elif hms_idx > idx: hms = info.hms(tokens[hms_idx]) new_idx = hms_idx else: # Looking backwards, increment one. hms = info.hms(tokens[hms_idx]) + 1 new_idx = idx return (new_idx, hms) # ------------------------------------------------------------------ # Handling for individual tokens. These are kept as methods instead # of functions for the sake of customizability via subclassing. def _parsems(self, value): """Parse a I[.F] seconds value into (seconds, microseconds).""" if "." not in value: return int(value), 0 else: i, f = value.split(".") return int(i), int(f.ljust(6, "0")[:6]) def _to_decimal(self, val): try: decimal_value = Decimal(val) # See GH 662, edge case, infinite value should not be converted # via `_to_decimal` if not decimal_value.is_finite(): raise ValueError("Converted decimal value is infinite or NaN") except Exception as e: msg = "Could not convert %s to decimal" % val raise ValueError(msg) from e else: return decimal_value # ------------------------------------------------------------------ # Post-Parsing construction of datetime output. These are kept as # methods instead of functions for the sake of customizability via # subclassing. def _build_tzinfo(self, tzinfos, tzname, tzoffset): if callable(tzinfos): tzdata = tzinfos(tzname, tzoffset) else: tzdata = tzinfos.get(tzname) # handle case where tzinfo is paased an options that returns None # eg tzinfos = {'BRST' : None} if isinstance(tzdata, datetime.tzinfo) or tzdata is None: tzinfo = tzdata elif isinstance(tzdata, str): tzinfo = tz.tzstr(tzdata) elif isinstance(tzdata, int): tzinfo = tz.tzoffset(tzname, tzdata) else: raise TypeError("Offset must be tzinfo subclass, tz string, " "or int offset.") return tzinfo def _build_tzaware(self, naive, res, tzinfos): if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) aware = naive.replace(tzinfo=tzinfo) aware = self._assign_tzname(aware, res.tzname) elif res.tzname and res.tzname in time.tzname: aware = naive.replace(tzinfo=tz.tzlocal()) # Handle ambiguous local datetime aware = self._assign_tzname(aware, res.tzname) # This is mostly relevant for winter GMT zones parsed in the UK if (aware.tzname() != res.tzname and res.tzname in self.info.UTCZONE): aware = aware.replace(tzinfo=tz.UTC) elif res.tzoffset == 0: aware = naive.replace(tzinfo=tz.UTC) elif res.tzoffset: aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) elif not res.tzname and not res.tzoffset: # i.e. no timezone information was found. aware = naive elif res.tzname: # tz-like string was parsed but we don't know what to do # with it warnings.warn("tzname {tzname} identified but not understood. " "Pass `tzinfos` argument in order to correctly " "return a timezone-aware datetime. In a future " "version, this will raise an " "exception.".format(tzname=res.tzname), category=UnknownTimezoneWarning) aware = naive return aware def _build_naive(self, res, default): repl = {} for attr in ("year", "month", "day", "hour", "minute", "second", "microsecond"): value = getattr(res, attr) if value is not None: repl[attr] = value if 'day' not in repl: # If the default day exceeds the last day of the month, fall back # to the end of the month. cyear = default.year if res.year is None else res.year cmonth = default.month if res.month is None else res.month cday = default.day if res.day is None else res.day if cday > monthrange(cyear, cmonth)[1]: repl['day'] = monthrange(cyear, cmonth)[1] naive = default.replace(**repl) if res.weekday is not None and not res.day: naive = naive + relativedelta.relativedelta(weekday=res.weekday) return naive def _assign_tzname(self, dt, tzname): if dt.tzname() != tzname: new_dt = tz.enfold(dt, fold=1) if new_dt.tzname() == tzname: return new_dt return dt def _recombine_skipped(self, tokens, skipped_idxs): """ >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] >>> skipped_idxs = [0, 1, 2, 5] >>> _recombine_skipped(tokens, skipped_idxs) ["foo bar", "baz"] """ skipped_tokens = [] for i, idx in enumerate(sorted(skipped_idxs)): if i > 0 and idx - 1 == skipped_idxs[i - 1]: skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] else: skipped_tokens.append(tokens[idx]) return skipped_tokens DEFAULTPARSER = parser() def parse(timestr, parserinfo=None, **kwargs): """ Parse a string in one of the supported formats, using the ``parserinfo`` parameters. :param timestr: A string containing a date/time stamp. :param parserinfo: A :class:`parserinfo` object containing parameters for the parser. If ``None``, the default arguments to the :class:`parserinfo` constructor are used. The ``**kwargs`` parameter takes the following keyword arguments: :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. If set to ``None``, this value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to ``None``, the value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param fuzzy: Whether to allow fuzzy parsing, allowing for string like "Today is January 1, 2047 at 8:21:00AM". :param fuzzy_with_tokens: If ``True``, ``fuzzy`` is automatically set to True, and the parser will return a tuple where the first element is the parsed :class:`datetime.datetime` datetimestamp and the second element is a tuple containing the portions of the string which were ignored: .. doctest:: >>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ParserError: Raised for invalid or unknown string formats, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. """ if parserinfo: return parser(parserinfo).parse(timestr, **kwargs) else: return DEFAULTPARSER.parse(timestr, **kwargs) class _tzparser: class _result(_resultbase): __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", "start", "end"] class _attr(_resultbase): __slots__ = ["month", "week", "weekday", "yday", "jyday", "day", "time"] def __repr__(self): return self._repr("") def __init__(self): _resultbase.__init__(self) self.start = self._attr() self.end = self._attr() def parse(self, tzstr): res = self._result() l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] used_idxs = list() try: len_l = len(l) i = 0 while i < len_l: # BRST+3[BRDT[+2]] j = i while j < len_l and not [x for x in l[j] if x in "0123456789:,-+"]: j += 1 if j != i: if not res.stdabbr: offattr = "stdoffset" res.stdabbr = "".join(l[i:j]) else: offattr = "dstoffset" res.dstabbr = "".join(l[i:j]) for ii in range(j): used_idxs.append(ii) i = j if (i < len_l and (l[i] in ('+', '-') or l[i][0] in "0123456789")): if l[i] in ('+', '-'): # Yes, that's right. See the TZ variable # documentation. signal = (1, -1)[l[i] == '+'] used_idxs.append(i) i += 1 else: signal = -1 len_li = len(l[i]) if len_li == 4: # -0300 setattr(res, offattr, (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) * signal) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 setattr(res, offattr, (int(l[i]) * 3600 + int(l[i + 2]) * 60) * signal) used_idxs.append(i) i += 2 elif len_li <= 2: # -[0]3 setattr(res, offattr, int(l[i][:2]) * 3600 * signal) else: return None used_idxs.append(i) i += 1 if res.dstabbr: break else: break if i < len_l: for j in range(i, len_l): if l[j] == ';': l[j] = ',' assert l[i] == ',' i += 1 if i >= len_l: pass elif (8 <= l.count(',') <= 9 and not [y for x in l[i:] if x != ',' for y in x if y not in "0123456789+-"]): # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] for x in (res.start, res.end): x.month = int(l[i]) used_idxs.append(i) i += 2 if l[i] == '-': value = int(l[i + 1]) * -1 used_idxs.append(i) i += 1 else: value = int(l[i]) used_idxs.append(i) i += 2 if value: x.week = value x.weekday = (int(l[i]) - 1) % 7 else: x.day = int(l[i]) used_idxs.append(i) i += 2 x.time = int(l[i]) used_idxs.append(i) i += 2 if i < len_l: if l[i] in ('-', '+'): signal = (-1, 1)[l[i] == "+"] used_idxs.append(i) i += 1 else: signal = 1 used_idxs.append(i) res.dstoffset = (res.stdoffset + int(l[i]) * signal) # This was a made-up format that is not in normal use warn(('Parsed time zone "%s"' % tzstr) + 'is in a non-standard dateutil-specific format, which ' + 'is now deprecated; support for parsing this format ' + 'will be removed in future versions. It is recommended ' + 'that you switch to a standard format like the GNU ' + 'TZ variable format.', tz.DeprecatedTzFormatWarning) elif (l.count(',') == 2 and l[i:].count('/') <= 2 and not [y for x in l[i:] if x not in (',', '/', 'J', 'M', '.', '-', ':') for y in x if y not in "0123456789"]): for x in (res.start, res.end): if l[i] == 'J': # non-leap year day (1 based) used_idxs.append(i) i += 1 x.jyday = int(l[i]) elif l[i] == 'M': # month[-.]week[-.]weekday used_idxs.append(i) i += 1 x.month = int(l[i]) used_idxs.append(i) i += 1 assert l[i] in ('-', '.') used_idxs.append(i) i += 1 x.week = int(l[i]) if x.week == 5: x.week = -1 used_idxs.append(i) i += 1 assert l[i] in ('-', '.') used_idxs.append(i) i += 1 x.weekday = (int(l[i]) - 1) % 7 else: # year day (zero based) x.yday = int(l[i]) + 1 used_idxs.append(i) i += 1 if i < len_l and l[i] == '/': used_idxs.append(i) i += 1 # start time len_li = len(l[i]) if len_li == 4: # -0300 x.time = (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 used_idxs.append(i) i += 2 if i + 1 < len_l and l[i + 1] == ':': used_idxs.append(i) i += 2 x.time += int(l[i]) elif len_li <= 2: # -[0]3 x.time = (int(l[i][:2]) * 3600) else: return None used_idxs.append(i) i += 1 assert i == len_l or l[i] == ',' i += 1 assert i >= len_l except (IndexError, ValueError, AssertionError): return None unused_idxs = set(range(len_l)).difference(used_idxs) res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) return res DEFAULTTZPARSER = _tzparser() def _parsetz(tzstr): return DEFAULTTZPARSER.parse(tzstr) class ParserError(ValueError): """Exception subclass used for any failure to parse a datetime string. This is a subclass of :py:exc:`ValueError`, and should be raised any time earlier versions of ``dateutil`` would have raised ``ValueError``. .. versionadded:: 2.8.1 """ def __str__(self): try: return self.args[0] % self.args[1:] except (TypeError, IndexError): return super().__str__() def __repr__(self): args = ", ".join("'%s'" % arg for arg in self.args) return "%s(%s)" % (self.__class__.__name__, args) class UnknownTimezoneWarning(RuntimeWarning): """Raised when the parser finds a timezone it cannot parse into a tzinfo. .. versionadded:: 2.7.0 """ # vim:ts=4:sw=4:et python_dateutil-4.0.0/src/dateutil/parser/isoparser.py0000644000000000000000000003272113615410400020133 0ustar00""" This module offers a parser for ISO-8601 strings It is intended to support all valid date, time and datetime formats per the ISO-8601 specification. ..versionadded:: 2.7.0 """ from datetime import datetime, timedelta, time, date import calendar from dateutil import tz from functools import wraps import re __all__ = ["isoparse", "isoparser"] def _takes_ascii(f): @wraps(f) def func(self, str_in, *args, **kwargs): # If it's a stream, read the whole thing str_in = getattr(str_in, 'read', lambda: str_in)() # If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII if isinstance(str_in, str): # ASCII is the same in UTF-8 try: str_in = str_in.encode('ascii') except UnicodeEncodeError as e: msg = 'ISO-8601 strings should contain only ASCII characters' raise ValueError(msg) from e return f(self, str_in, *args, **kwargs) return func class isoparser: def __init__(self, sep=None): """ :param sep: A single character that separates date and time portions. If ``None``, the parser will accept any single character. For strict ISO-8601 adherence, pass ``'T'``. """ if sep is not None: if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): raise ValueError('Separator must be a single, non-numeric ' + 'ASCII character') sep = sep.encode('ascii') self._sep = sep @_takes_ascii def isoparse(self, dt_str): """ Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion - the date and time portions are separated by a single character separator, which is ``T`` in the official standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be combined with a time portion. Supported date formats are: Common: - ``YYYY`` - ``YYYY-MM`` - ``YYYY-MM-DD`` or ``YYYYMMDD`` Uncommon: - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day The ISO week and day numbering follows the same logic as :func:`datetime.date.isocalendar`. Supported time formats are: - ``hh`` - ``hh:mm`` or ``hhmm`` - ``hh:mm:ss`` or ``hhmmss`` - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) Midnight is a special case for `hh`, as the standard supports both 00:00 and 24:00 as a representation. The decimal separator can be either a dot or a comma. .. caution:: Support for fractional components other than seconds is part of the ISO-8601 standard, but is not currently implemented in this parser. Supported time zone offset formats are: - `Z` (UTC) - `±HH:MM` - `±HHMM` - `±HH` Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, with the exception of UTC, which will be represented as :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. :param dt_str: A string or stream containing only an ISO-8601 datetime string :return: Returns a :class:`datetime.datetime` representing the string. Unspecified components default to their lowest value. .. warning:: As of version 2.7.0, the strictness of the parser should not be considered a stable part of the contract. Any valid ISO-8601 string that parses correctly with the default settings will continue to parse correctly in future versions, but invalid strings that currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not guaranteed to continue failing in future versions if they encode a valid date. .. versionadded:: 2.7.0 """ components, pos = self._parse_isodate(dt_str) if len(dt_str) > pos: if self._sep is None or dt_str[pos:pos + 1] == self._sep: components += self._parse_isotime(dt_str[pos + 1:]) else: raise ValueError('String contains unknown ISO components') if len(components) > 3 and components[3] == 24: components[3] = 0 return datetime(*components) + timedelta(days=1) return datetime(*components) @_takes_ascii def parse_isodate(self, datestr): """ Parse the date portion of an ISO string. :param datestr: The string portion of an ISO string, without a separator :return: Returns a :class:`datetime.date` object """ components, pos = self._parse_isodate(datestr) if pos < len(datestr): raise ValueError('String contains unknown ISO ' + 'components: {!r}'.format(datestr.decode('ascii'))) return date(*components) @_takes_ascii def parse_isotime(self, timestr): """ Parse the time portion of an ISO string. :param timestr: The time portion of an ISO string, without a separator :return: Returns a :class:`datetime.time` object """ components = self._parse_isotime(timestr) if components[0] == 24: components[0] = 0 return time(*components) @_takes_ascii def parse_tzstr(self, tzstr, zero_as_utc=True): """ Parse a valid ISO time zone string. See :func:`isoparser.isoparse` for details on supported formats. :param tzstr: A string representing an ISO time zone offset :param zero_as_utc: Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones :return: Returns :class:`dateutil.tz.tzoffset` for offsets and :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is specified) offsets equivalent to UTC. """ return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) # Constants _DATE_SEP = b'-' _TIME_SEP = b':' _FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)') def _parse_digits(self, s, pos, n): """Parse exactly ``n`` ASCII digits starting at ``pos``.""" digits = s[pos : pos + n] if len(digits) != n or not digits.isdigit(): raise ValueError( "Expected {} digits, got {!r}".format(n, digits.decode("ascii")) ) return int(digits) def _parse_isodate(self, dt_str): try: return self._parse_isodate_common(dt_str) except ValueError: return self._parse_isodate_uncommon(dt_str) def _parse_isodate_common(self, dt_str): len_str = len(dt_str) components = [1, 1, 1] if len_str < 4: raise ValueError('ISO string too short') # Year components[0] = self._parse_digits(dt_str, 0, 4) pos = 4 if pos >= len_str: return components, pos has_sep = dt_str[pos:pos + 1] == self._DATE_SEP if has_sep: pos += 1 # Month if len_str - pos < 2: raise ValueError('Invalid common month') components[1] = self._parse_digits(dt_str, pos, 2) pos += 2 if pos >= len_str: if has_sep: return components, pos else: raise ValueError('Invalid ISO format') if has_sep: if dt_str[pos:pos + 1] != self._DATE_SEP: raise ValueError('Invalid separator in ISO string') pos += 1 # Day if len_str - pos < 2: raise ValueError('Invalid common day') components[2] = self._parse_digits(dt_str, pos, 2) return components, pos + 2 def _parse_isodate_uncommon(self, dt_str): if len(dt_str) < 4: raise ValueError('ISO string too short') # All ISO formats start with the year year = self._parse_digits(dt_str, 0, 4) has_sep = dt_str[4:5] == self._DATE_SEP pos = 4 + has_sep # Skip '-' if it's there if dt_str[pos:pos + 1] == b'W': # YYYY-?Www-?D? pos += 1 weekno = self._parse_digits(dt_str, pos, 2) pos += 2 dayno = 1 if len(dt_str) > pos: if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep: raise ValueError('Inconsistent use of dash separator') pos += has_sep dayno = self._parse_digits(dt_str, pos, 1) pos += 1 base_date = self._calculate_weekdate(year, weekno, dayno) else: # YYYYDDD or YYYY-DDD if len(dt_str) - pos < 3: raise ValueError('Invalid ordinal day') ordinal_day = self._parse_digits(dt_str, pos, 3) pos += 3 if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)): raise ValueError('Invalid ordinal day' + ' {} for year {}'.format(ordinal_day, year)) base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1) components = [base_date.year, base_date.month, base_date.day] return components, pos def _calculate_weekdate(self, year, week, day): """ Calculate the day of corresponding to the ISO year-week-day calendar. This function is effectively the inverse of :func:`datetime.date.isocalendar`. :param year: The year in the ISO calendar :param week: The week in the ISO calendar - range is [1, 53] :param day: The day in the ISO calendar - range is [1 (MON), 7 (SUN)] :return: Returns a :class:`datetime.date` """ if not 0 < week < 54: raise ValueError('Invalid week: {}'.format(week)) if not 0 < day < 8: # Range is 1-7 raise ValueError('Invalid weekday: {}'.format(day)) # Get week 1 for the specific year: jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1) # Now add the specific number of weeks and days to get what we want week_offset = (week - 1) * 7 + (day - 1) return week_1 + timedelta(days=week_offset) def _parse_isotime(self, timestr): len_str = len(timestr) components = [0, 0, 0, 0, None] pos = 0 comp = -1 if len_str < 2: raise ValueError('ISO time too short') has_sep = False while pos < len_str and comp < 5: comp += 1 if timestr[pos:pos + 1] in b'-+Zz': # Detect time zone boundary components[-1] = self._parse_tzstr(timestr[pos:]) pos = len_str break if comp == 1 and timestr[pos:pos+1] == self._TIME_SEP: has_sep = True pos += 1 elif comp == 2 and has_sep: if timestr[pos:pos+1] != self._TIME_SEP: raise ValueError('Inconsistent use of colon separator') pos += 1 if comp < 3: # Hour, minute, second components[comp] = self._parse_digits(timestr, pos, 2) pos += 2 if comp == 3: # Fraction of a second frac = self._FRACTION_REGEX.match(timestr[pos:]) if not frac: continue us_str = frac.group(1)[:6] # Truncate to microseconds components[comp] = int(us_str) * 10**(6 - len(us_str)) pos += len(frac.group()) if pos < len_str: raise ValueError('Unused components in ISO string') if components[0] == 24: # Standard supports 00:00 and 24:00 as representations of midnight if any(component != 0 for component in components[1:4]): raise ValueError('Hour may only be 24 at 24:00:00.000') return components def _parse_tzstr(self, tzstr, zero_as_utc=True): if tzstr == b'Z' or tzstr == b'z': return tz.UTC if len(tzstr) not in {3, 5, 6}: raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters') if tzstr[0:1] == b'-': mult = -1 elif tzstr[0:1] == b'+': mult = 1 else: raise ValueError('Time zone offset requires sign') hours = self._parse_digits(tzstr, 1, 2) if len(tzstr) == 3: minutes = 0 else: pos = 4 if tzstr[3:4] == self._TIME_SEP else 3 if len(tzstr) != pos + 2: raise ValueError("Invalid minutes in time zone offset") minutes = self._parse_digits(tzstr, pos, 2) if zero_as_utc and hours == 0 and minutes == 0: return tz.UTC else: if minutes > 59: raise ValueError('Invalid minutes in time zone offset') if hours > 23: raise ValueError('Invalid hours in time zone offset') return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) DEFAULT_ISOPARSER = isoparser() isoparse = DEFAULT_ISOPARSER.isoparse python_dateutil-4.0.0/src/dateutil/tz/__init__.py0000644000000000000000000000155413615410400017024 0ustar00from . import _tzpath from ._tzpath import reset_tzpath from .tz import * from .tz import __doc__ __all__ = [ "tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz", "enfold", "datetime_ambiguous", "datetime_exists", "resolve_imaginary", "available_iana_timezones", "UTC", "TZPATH", "reset_tzpath", "DeprecatedTzFormatWarning", "DeprecatedTzKeyWarning", ] def __getattr__(name): if name == "TZPATH": return _tzpath.TZPATH else: raise AttributeError( "Module %s has no attribute %s" % (repr(__name__), repr(name)) ) def __dir__(): return sorted(list(globals()) + ["TZPATH"]) class DeprecatedTzFormatWarning(Warning): """Warning raised when time zones are parsed from deprecated formats.""" python_dateutil-4.0.0/src/dateutil/tz/_common.py0000644000000000000000000002202713615410400016712 0ustar00 from functools import wraps from datetime import datetime, timedelta, tzinfo ZERO = timedelta(0) __all__ = ["enfold"] # The following is adapted from Alexander Belopolsky's tz library # https://github.com/abalkin/tz def enfold(dt: datetime, fold: int = 1) -> datetime: """Returns a datetime with the ``fold`` attribute set to ``fold``. :param fold: The value for the ``fold`` attribute, either 0 or 1. :return: A :class:`datetime.datetime` with the requested ``fold`` value. .. versionadded:: 2.6.0 """ return dt.replace(fold=fold) def _validate_fromutc_inputs(f): """ The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``. """ @wraps(f) def fromutc(self, dt): if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") return f(self, dt) return fromutc class _tzinfo(tzinfo): """ Base class for all ``dateutil`` ``tzinfo`` objects. """ def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ dt = dt.replace(tzinfo=self) wall_0 = enfold(dt, fold=0) wall_1 = enfold(dt, fold=1) same_offset = wall_0.utcoffset() == wall_1.utcoffset() same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None) return same_dt and not same_offset def _fold_status(self, dt_utc, dt_wall): """ Determine the fold status of a "wall" datetime, given a representation of the same datetime as a (naive) UTC datetime. This is calculated based on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all datetimes, and that this offset is the actual number of hours separating ``dt_utc`` and ``dt_wall``. :param dt_utc: Representation of the datetime as UTC :param dt_wall: Representation of the datetime as "wall time". This parameter must either have a `fold` attribute or have a fold-naive :class:`datetime.tzinfo` attached, otherwise the calculation may fail. """ if self.is_ambiguous(dt_wall): delta_wall = dt_wall - dt_utc _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst())) else: _fold = 0 return _fold def _fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurrence, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ # Re-implement the algorithm from Python's datetime.py dtoff = dt.utcoffset() if dtoff is None: raise ValueError("fromutc() requires a non-None utcoffset() " "result") # The original datetime.py code assumes that `dst()` defaults to # zero during ambiguous times. PEP 495 inverts this presumption, so # select fold=1 when calculating the DST adjustment below. dtdst = dt.dst() if dtdst is None: raise ValueError("fromutc() requires a non-None dst() result") delta = dtoff - dtdst dt += delta # Set fold=1 so we can default to being in the fold for # ambiguous dates. dtdst = enfold(dt, fold=1).dst() if dtdst is None: raise ValueError("fromutc(): dt.dst gave inconsistent " "results; cannot convert") return dt + dtdst @_validate_fromutc_inputs def fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurrence, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ dt_wall = self._fromutc(dt) # Calculate the fold status given the two datetimes. _fold = self._fold_status(dt, dt_wall) # Set the default fold value for ambiguous dates return enfold(dt_wall, fold=_fold) class tzrangebase(_tzinfo): """ This is an abstract base class for time zones represented by an annual transition into and out of DST. Child classes should implement the following methods: * ``__init__(self, *args, **kwargs)`` * ``transitions(self, year)`` - this is expected to return a tuple of datetimes representing the DST on and off transitions in standard time. A fully initialized ``tzrangebase`` subclass should also provide the following attributes: * ``hasdst``: Boolean whether or not the zone uses DST. * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects representing the respective UTC offsets. * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short abbreviations in DST and STD, respectively. * ``_hasdst``: Whether or not the zone has DST. .. versionadded:: 2.6.0 """ def __init__(self): raise NotImplementedError('tzrangebase is an abstract base class') def utcoffset(self, dt): isdst = self._isdst(dt) if isdst is None: return None elif isdst: return self._dst_offset else: return self._std_offset def dst(self, dt): isdst = self._isdst(dt) if isdst is None: return None elif isdst: return self._dst_base_offset else: return ZERO def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def fromutc(self, dt): """ Given a datetime in UTC, return local time """ if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # Get transitions - if there are none, fixed offset transitions = self.transitions(dt.year) if transitions is None: return dt + self.utcoffset(dt) # Get the transition times in UTC dston, dstoff = transitions dston -= self._std_offset dstoff -= self._std_offset utc_transitions = (dston, dstoff) dt_utc = dt.replace(tzinfo=None) isdst = self._naive_isdst(dt_utc, utc_transitions) if isdst: dt_wall = dt + self._dst_offset else: dt_wall = dt + self._std_offset _fold = int(not isdst and self.is_ambiguous(dt_wall)) return enfold(dt_wall, fold=_fold) def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ if not self.hasdst: return False start, end = self.transitions(dt.year) dt = dt.replace(tzinfo=None) return (end <= dt < end + self._dst_base_offset) def _isdst(self, dt): if not self.hasdst: return False elif dt is None: return None transitions = self.transitions(dt.year) if transitions is None: return False dt = dt.replace(tzinfo=None) isdst = self._naive_isdst(dt, transitions) # Handle ambiguous dates if not isdst and self.is_ambiguous(dt): return not dt.fold else: return isdst def _naive_isdst(self, dt, transitions): dston, dstoff = transitions dt = dt.replace(tzinfo=None) if dston < dstoff: isdst = dston <= dt < dstoff else: isdst = not dstoff <= dt < dston return isdst @property def _dst_base_offset(self): return self._dst_offset - self._std_offset __hash__ = None def __repr__(self): return "%s(...)" % self.__class__.__name__ __reduce__ = object.__reduce__ python_dateutil-4.0.0/src/dateutil/tz/_factories.py0000644000000000000000000000472613615410400017407 0ustar00import _thread import weakref from collections import OrderedDict from datetime import timedelta class _TzSingleton(type): def __init__(cls, *args, **kwargs): cls.__instance = None super().__init__(*args, **kwargs) def __call__(cls): if cls.__instance is None: cls.__instance = super().__call__() return cls.__instance class _TzFactory(type): def instance(cls, *args, **kwargs): """Alternate constructor that returns a fresh instance""" return type.__call__(cls, *args, **kwargs) class _TzOffsetFactory(_TzFactory): def __init__(cls, *args, **kwargs): cls.__instances = weakref.WeakValueDictionary() cls.__strong_cache = OrderedDict() cls.__strong_cache_size = 8 cls._cache_lock = _thread.allocate_lock() def __call__(cls, name, offset): if isinstance(offset, timedelta): key = (name, offset.total_seconds()) else: key = (name, offset) instance = cls.__instances.get(key, None) if instance is None: instance = cls.__instances.setdefault(key, cls.instance(name, offset)) # This lock may not be necessary in Python 3. See GH issue #901 with cls._cache_lock: cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) # Remove an item if the strong cache is overpopulated if len(cls.__strong_cache) > cls.__strong_cache_size: cls.__strong_cache.popitem(last=False) return instance class _TzStrFactory(_TzFactory): def __init__(cls, *args, **kwargs): cls.__instances = weakref.WeakValueDictionary() cls.__strong_cache = OrderedDict() cls.__strong_cache_size = 8 cls.__cache_lock = _thread.allocate_lock() def __call__(cls, s, posix_offset=False): key = (s, posix_offset) instance = cls.__instances.get(key, None) if instance is None: instance = cls.__instances.setdefault(key, cls.instance(s, posix_offset)) # This lock may not be necessary in Python 3. See GH issue #901 with cls.__cache_lock: cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) # Remove an item if the strong cache is overpopulated if len(cls.__strong_cache) > cls.__strong_cache_size: cls.__strong_cache.popitem(last=False) return instance python_dateutil-4.0.0/src/dateutil/tz/_tzfile.py0000644000000000000000000013201413615410400016715 0ustar00import bisect import calendar import contextlib import functools import io import os import re import stat import struct import sys from datetime import MAXYEAR, MINYEAR, datetime, timedelta from ._common import _tzinfo, enfold EPOCH = datetime(1970, 1, 1) EPOCHORDINAL = EPOCH.toordinal() # It is relatively expensive to construct new timedelta objects, and in most # cases we're looking at the same deltas, like integer numbers of hours, etc. # To improve speed and memory use, we'll keep a dictionary with references # to the ones we've already used so far. # # Loading every time zone in the 2020a version of the time zone database # requires 447 timedeltas, which requires approximately the amount of space # that ZoneInfo("America/New_York") with 236 transitions takes up, so we will # set the cache size to 512 so that in the common case we always get cache # hits, but specifically crafted ZoneInfo objects don't leak arbitrary amounts # of memory. _TIMEDELTA_CACHE_SIZE = 512 @functools.lru_cache(maxsize=_TIMEDELTA_CACHE_SIZE) def _load_timedelta(seconds): return timedelta(seconds=seconds) def _unpickle(cls, key, filename, data): obj = cls.__new__(cls) obj._key = key obj._filename = filename obj._load_from_data(data) return obj class tzfile(_tzinfo): """ This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)`` format timezone files to extract current and historical zone information. :param fileobj: This can be an opened file stream or a file name that the time zone information can be read from. :param filename: This is an optional parameter specifying the source of the time zone information in the event that ``fileobj`` is a file object. If omitted and ``fileobj`` is a file stream, this parameter will be set either to ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. This class is intended to be mostly equivalent to the standard library :py:class:`zoneinfo.ZoneInfo` class. The primary differences are: * All caching in ``tzfile`` is handled by :func:`tz.gettz` level (you should generally not attempt to construct a ``tzfile`` directly). * ``tzfile`` objects are pickled by value rather than by reference to the IANA key. * ``tzfile`` has equality-by-value semantics, whereas :py:class:`~zoneinfo.ZoneInfo` has equality-by-identity semantics. See `Sources for Time Zone and Daylight Saving Time Data `_ for more information. Time zone files can be compiled from the `IANA Time Zone database files `_ with the `zic time zone compiler `_ .. note:: Only construct a ``tzfile`` directly if you have a specific timezone file on disk that you want to read into a Python ``tzinfo`` object. If you want to get a ``tzfile`` representing a specific IANA zone, (e.g. ``'America/New_York'``), you should call :func:`dateutil.tz.gettz` with the zone identifier. .. versionchanged:: 3.0.0 ``tzfile`` is now a partial backport of :py:class:`zoneinfo.ZoneInfo`, which brings with it support for Version 2 and 3 ``tzfile(5)`` binaries. **Examples:** Using the US Eastern time zone as an example, we can see that a ``tzfile`` provides time zone information for the standard Daylight Saving offsets: .. testsetup:: tzfile from dateutil.tz import gettz from datetime import datetime .. doctest:: tzfile >>> NYC = gettz('America/New_York') >>> NYC tzfile('/usr/share/zoneinfo/America/New_York') >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST 2016-01-03 00:00:00-05:00 >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT 2016-07-07 00:00:00-04:00 The ``tzfile`` structure contains a fully history of the time zone, so historical dates will also have the right offsets. For example, before the adoption of standard time on November 18, 1883, New York used local mean time: .. doctest:: tzfile >>> print(datetime(1883, 11, 18, tzinfo=NYC)) # LMT 1883-11-18 00:00:00-04:56:02 And during World War II, New York was on "Eastern War Time", which was a state of permanent daylight saving time: .. doctest:: tzfile >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT 1944-02-07 00:00:00-04:00 """ def __init__(self, fileobj, filename=None, key=None): super().__init__() file_opened_here = False if isinstance(fileobj, str): self._filename = fileobj fileobj = open(fileobj, "rb") file_opened_here = True elif filename is not None: self._filename = filename elif hasattr(fileobj, "name"): self._filename = fileobj.name elif key is not None: self._filename = key else: self._filename = repr(fileobj) if fileobj is not None: if not file_opened_here: fileobj = contextlib.nullcontext(fileobj) with fileobj as file_stream: self._load_file(file_stream) self._key = key @property def key(self): """ Read-only attribute returning the ``key`` constructor argument. For zones generated from :func:`gettz`, this will be the IANA key passed to ``gettz`` — no normalization is done, so although in most distributions of the time zone database "US/Eastern" is a link to "America/New_York", ``tz.gettz("US/Eastern").key`` should always return ``"US/Eastern"``. For zones constructed via another mechanism without specifying ``key``, this returns :obj:`None`. """ return self._key def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ return self._is_ambiguous_or_imaginary(dt) == 1 def _is_ambiguous_or_imaginary(self, dt): if dt is None or self._fixed_offset: return 0 timestamp = self._get_local_timestamp(dt) tti_0 = self._find_trans(dt, fold=0, timestamp=timestamp) tti_1 = self._find_trans(dt, fold=1, timestamp=timestamp) # Returns 1 if ambiguous, -1 if imaginary and 0 otherwise. return int(tti_0.utcoff > tti_1.utcoff) - int( tti_1.utcoff > tti_0.utcoff ) def utcoffset(self, dt): return self._find_trans(dt).utcoff def dst(self, dt): return self._find_trans(dt).dstoff def tzname(self, dt): return self._find_trans(dt).tzname def fromutc(self, dt): """ The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. :param dt: A :py:class:`datetime.datetime` object. :raises TypeError: Raised if ``dt`` is not a :py:class:`datetime.datetime` object. :raises ValueError: Raised if this is called with a ``dt`` which does not have this ``tzinfo`` attached. :return: Returns a :py:class:`datetime.datetime` object representing the wall time in ``self``'s time zone. """ if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") timestamp = self._get_local_timestamp(dt) num_trans = len(self._trans_utc) if num_trans >= 1 and timestamp < self._trans_utc[0]: tti = self._tti_before fold = 0 elif ( num_trans == 0 or timestamp > self._trans_utc[-1] ) and not isinstance(self._tz_after, _ttinfo): tti, fold = self._tz_after.get_trans_info_fromutc( timestamp, dt.year ) # The TZ string only knows about its own transitions, so check # whether we are in a fold created by the last explicit one. if num_trans and not fold: if num_trans > 1: tti_prev = self._ttinfos[-2] else: tti_prev = self._tti_before shift = tti_prev.utcoff - tti.utcoff fold = shift.total_seconds() > timestamp - self._trans_utc[-1] elif num_trans == 0: tti = self._tz_after fold = 0 else: idx = bisect.bisect_right(self._trans_utc, timestamp) if num_trans > 1 and timestamp >= self._trans_utc[1]: tti_prev, tti = self._ttinfos[idx - 2 : idx] elif timestamp > self._trans_utc[-1]: # Only reachable with exactly one transition, so the # offset before it is _tti_before, not _ttinfos[-1]. tti_prev = self._tti_before tti = self._tz_after else: tti_prev = self._tti_before tti = self._ttinfos[0] # Detect fold shift = tti_prev.utcoff - tti.utcoff fold = shift.total_seconds() > timestamp - self._trans_utc[idx - 1] dt += tti.utcoff if fold: return enfold(dt, fold=1) else: return dt def _find_trans(self, dt, fold=None, timestamp=None): if dt is None: if self._fixed_offset: return self._tz_after else: return _NO_TTINFO if timestamp is None: ts = self._get_local_timestamp(dt) else: ts = timestamp if fold is None: fold = dt.fold lt = self._trans_local[fold] num_trans = len(lt) if num_trans and ts < lt[0]: return self._tti_before elif not num_trans or ts > lt[-1]: if isinstance(self._tz_after, _TZStr): tti = self._tz_after.get_trans_info(ts, dt.year, fold) # The TZ string only describes times after the last explicit # transition. If its answer for this local time is a different # offset from the last transition's, and corresponds to a time # before that transition (e.g. when the TZ string's own DST # period for that year ends after the transition), the offset # from the last explicit transition applies instead. last_tti = self._ttinfos[-1] if num_trans else None if ( last_tti is not None and tti.utcoff != last_tti.utcoff and ts - tti.utcoff.total_seconds() < self._trans_utc[-1] ): return last_tti return tti else: return self._tz_after else: # idx is the transition that occurs after this timestamp, so we # subtract off 1 to get the current ttinfo idx = bisect.bisect_right(lt, ts) - 1 assert idx >= 0 return self._ttinfos[idx] def _get_local_timestamp(self, dt): return ( (dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour * 3600 + dt.minute * 60 + dt.second ) # The attributes set by _unpickle and _load_from_data _UNPICKLE_ATTRS = frozenset( [ "_filename", "_fixed_offset", "_isdst", "_key", "_trans_idx", "_trans_local", "_trans_utc", "_tti_before", "_ttinfo_list", "_ttinfos", "_tz_after", "_tz_str", ] ) def __reduce__(self): return self.__reduce_ex__(None) def __reduce_ex__(self, protocol): utcoff = [ int(ttinfo.utcoff.total_seconds()) for ttinfo in self._ttinfo_list ] abbr = [ttinfo.tzname for ttinfo in self._ttinfo_list] # dst() is inferred per transition, so the transitions don't map back # to the local time types, and these are kept as they were in the file trans_idx = self._trans_idx isdst = self._isdst trans_utc = self._trans_utc tz_str = self._tz_str data = (trans_idx, trans_utc, utcoff, isdst, abbr, tz_str) args = (self.__class__, self._key, self._filename, data) # Preserve any other instance state, such as attributes added by a # subclass, but not the attributes that _unpickle rebuilds from data state = { k: v for k, v in vars(self).items() if k not in self._UNPICKLE_ATTRS } if state: return (_unpickle, args, state) return (_unpickle, args) def _load_file(self, fobj): # Reading the file requires seeking past the parts we don't use and # reading the footer a line at a time, so read anything that doesn't # support that (e.g. a pipe) into memory first; TZif files are small. if not _is_seekable(fobj) or not hasattr(fobj, "readline"): fobj = io.BytesIO(fobj.read()) # Retrieve all the data as it exists in the zoneinfo file data = load_data(fobj) self._load_from_data(data) def _load_from_data(self, data): trans_idx, trans_utc, utcoff, isdst, abbr, tz_str = data # Infer the DST offsets (needed for .dst()) from the data, for each # transition and for each local time type trans_dstoff = self._utcoff_to_dstoff( trans_idx, trans_utc, utcoff, isdst ) dstoff = [3600 if dst else 0 for dst in isdst] for idx, trans_off in zip(trans_idx, trans_dstoff): dstoff[idx] = trans_off # Convert all the transition times (UTC) into "seconds since 1970-01-01 local time" trans_local = self._ts_to_local(trans_idx, trans_utc, utcoff) # Construct `_ttinfo` objects for each transition in the file _ttinfo_list = [ _ttinfo( _load_timedelta(utcoffset), _load_timedelta(dstoffset), tzname ) for utcoffset, dstoffset, tzname in zip(utcoff, dstoff, abbr) ] self._ttinfo_list = _ttinfo_list self._trans_idx = trans_idx self._isdst = isdst self._trans_utc = trans_utc self._trans_local = trans_local # Transitions to the same local time type usually have the same DST # offset, so share the _ttinfo objects between them where possible. ttinfos = {} self._ttinfos = [] for idx, trans_off in zip(trans_idx, trans_dstoff): tti = _ttinfo_list[idx] if tti.dstoff.total_seconds() != trans_off: key = (idx, trans_off) if key not in ttinfos: ttinfos[key] = _ttinfo( tti.utcoff, _load_timedelta(trans_off), tti.tzname ) tti = ttinfos[key] self._ttinfos.append(tti) # Find the first non-DST transition for i in range(len(isdst)): if not isdst[i]: self._tti_before = _ttinfo_list[i] break else: if self._ttinfos: self._tti_before = self._ttinfos[0] else: self._tti_before = None # Set the "fallback" time zone self._tz_str = tz_str if tz_str is not None and tz_str != b"": self._tz_after = _parse_tz_str(tz_str.decode()) else: if not self._ttinfos and not _ttinfo_list: raise ValueError("No time zone information found.") if self._ttinfos: self._tz_after = self._ttinfos[-1] else: # With no transitions and no TZ string, RFC 9636 Section 3.2 # says that local time is specified by time type 0 self._tz_after = _ttinfo_list[0] # Determine if this is a "fixed offset" zone, meaning that the output # of the utcoffset, dst and tzname functions does not depend on the # specific datetime passed. # # We make three simplifying assumptions here: # # 1. If _tz_after is not a _ttinfo, it has transitions that might # actually occur (it is possible to construct TZ strings that # specify STD and DST but no transitions ever occur, such as # AAA0BBB,0/0,J365/25). # 2. If _ttinfo_list contains more than one _ttinfo object, the objects # represent different offsets. # 3. _ttinfo_list contains no unused _ttinfos (in which case an # otherwise fixed-offset zone with extra _ttinfos defined may # appear to *not* be a fixed offset zone). # # Violations to these assumptions would be fairly exotic, and exotic # zones should almost certainly not be used with datetime.time (the # only thing that would be affected by this). if len(_ttinfo_list) > 1 or not isinstance(self._tz_after, _ttinfo): self._fixed_offset = False elif not _ttinfo_list: self._fixed_offset = True else: self._fixed_offset = _ttinfo_list[0] == self._tz_after @staticmethod def _utcoff_to_dstoff(trans_idx, trans_utc, utcoffsets, isdsts): """Infer the DST offset (the value of dst()) for each transition. TZif files give the total UTC offset of each local time type and whether it is DST, but not how much of the offset is DST, so this has to be worked out from the standard time on either side of each DST period. That is done for each transition rather than for each local time type, because zic reuses a local time type for periods with different standard offsets (e.g. UTC+0 DST in the Azores was double summer time in the 1940s and summer time later). """ n = len(trans_idx) # The DST offset implied by the last standard time before and the # first standard time after each transition. Before the first # transition, it's the first standard time type, as for _tti_before. first_std_utcoff = next( (utcoff for utcoff, dst in zip(utcoffsets, isdsts) if not dst), None, ) before = [None] * n after = [None] * n for indices, implied, std_utcoff in ( (range(n), before, first_std_utcoff), (range(n - 1, -1, -1), after, None), ): for i in indices: idx = trans_idx[i] if not isdsts[idx]: std_utcoff = utcoffsets[idx] elif std_utcoff is not None: implied[i] = utcoffsets[idx] - std_utcoff # DST offsets where the standard time is the same on both sides clear_cut = [ (trans_utc[i], before[i]) for i in range(n) if before[i] and before[i] == after[i] ] dstoffs = [0] * n for i in range(n): if not isdsts[trans_idx[i]]: continue candidates = {c for c in (before[i], after[i]) if c} if len(candidates) > 1: # The standard offset changed during the DST period. A change # from local mean time can give something like 0:34:39, which # is not a plausible amount of DST. plausible = {c for c in candidates if c % 300 == 0} candidates = plausible or candidates if len(candidates) > 1: # Prefer the amount of DST the zone used around the same # time, e.g. Tehran used 1:00 and Rarotonga 0:30, though the # TZif data for Tehran in 1977 and for Rarotonga in 1978 look # the same. This has to be local in time, because some zones # used different amounts in different eras (e.g. Montevideo # used 0:30 in the 1920s and 1:00 later). nearby = { dstoff for ts, dstoff in clear_cut if abs(ts - trans_utc[i]) <= _DST_CONSENSUS_WINDOW } consensus = candidates & nearby if len(consensus) == 1: candidates = consensus if candidates: # Otherwise, prefer positive DST, then the smaller amount. In # the 1942 occupation zones, e.g. Europe/Kyiv, the standard # time before gives -1:00 and the one after +1:00. dstoffs[i] = min(candidates, key=lambda c: (c < 0, abs(c))) else: # Without any standard time to compare to, one hour is a much # better guess than 0 dstoffs[i] = 3600 return dstoffs @staticmethod def _ts_to_local(trans_idx, trans_list_utc, utcoffsets): """Generate number of seconds since 1970 *in the local time*. This is necessary to easily find the transition times in local time""" if not trans_list_utc: return [[], []] # Start with the timestamps and modify in-place trans_list_wall = [list(trans_list_utc), list(trans_list_utc)] if len(utcoffsets) > 1: offset_0 = utcoffsets[0] offset_1 = utcoffsets[trans_idx[0]] if offset_1 > offset_0: offset_1, offset_0 = offset_0, offset_1 else: offset_0 = offset_1 = utcoffsets[0] trans_list_wall[0][0] += offset_0 trans_list_wall[1][0] += offset_1 for i in range(1, len(trans_idx)): offset_0 = utcoffsets[trans_idx[i - 1]] offset_1 = utcoffsets[trans_idx[i]] if offset_1 > offset_0: offset_1, offset_0 = offset_0, offset_1 trans_list_wall[0][i] += offset_0 trans_list_wall[1][i] += offset_1 return trans_list_wall def __eq__(self, other): if not isinstance(other, tzfile): return NotImplemented return ( self._trans_utc == other._trans_utc and self._trans_local == other._trans_local and self._ttinfos == other._ttinfos and self._tti_before == other._tti_before and self._fallback_key() == other._fallback_key() ) def _fallback_key(self): # The behavior after the last transition is determined either by the # TZ string or, in its absence, by a single _ttinfo; _TZStr objects # do not define equality, so compare the string they came from. if isinstance(self._tz_after, _ttinfo): return self._tz_after return self._tz_str __hash__ = None def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) # Before Python 3.16, pipes on Windows claim to be seekable, but seeking on # them silently does nothing. See https://github.com/python/cpython/issues/86768 _SEEKABLE_PIPES_BUG = sys.platform == "win32" and sys.version_info < (3, 16) def _is_seekable(fobj): if not hasattr(fobj, "seek"): return False seekable = getattr(fobj, "seekable", None) # File-like objects need not implement seekable(). if seekable is not None and not seekable(): return False if not _SEEKABLE_PIPES_BUG: return True # For anything backed by a file descriptor, only trust regular files. try: fd = fobj.fileno() except (AttributeError, OSError, ValueError): # io.UnsupportedOperation (e.g. from BytesIO) is both of the latter return True try: return stat.S_ISREG(os.fstat(fd).st_mode) except OSError: return True def load_data(fobj): try: return _load_data(fobj) except struct.error as e: # struct.unpack fails when a read comes up short raise ValueError("Invalid TZif file: unexpected end of file") from e def _load_data(fobj): header = _TZifHeader.from_file(fobj) if header.version == 1: time_size = 4 time_type = "l" else: # Version 2+ has 64-bit integer transition times time_size = 8 time_type = "q" # Version 2+ also starts with a Version 1 header and data, which # we need to skip now skip_bytes = ( header.timecnt * 5 # Transition times and types + header.typecnt * 6 # Local time type records + header.charcnt # Time zone designations + header.leapcnt * 8 # Leap second records + header.isstdcnt # Standard/wall indicators + header.isutcnt # UT/local indicators ) fobj.seek(skip_bytes, 1) # Now we need to read the second header, which is not the same # as the first header = _TZifHeader.from_file(fobj) typecnt = header.typecnt timecnt = header.timecnt charcnt = header.charcnt # The data portion starts with timecnt transitions and indices if timecnt: trans_list_utc = struct.unpack( ">%s%s" % (timecnt, time_type), fobj.read(timecnt * time_size) ) trans_idx = struct.unpack(">%sB" % timecnt, fobj.read(timecnt)) if max(trans_idx) >= typecnt: raise ValueError( "Invalid transition index found while reading TZif: %s" % max(trans_idx) ) else: trans_list_utc = () trans_idx = () # Read the ttinfo struct, (utoff, isdst, abbrind) if typecnt: utcoff, isdst, abbrind = zip( *(struct.unpack(">lbb", fobj.read(6)) for i in range(typecnt)) ) else: utcoff = () isdst = () abbrind = () # Now read the abbreviations. They are null-terminated strings, indexed # not by position in the array but by position in the unsplit # abbreviation string. I suppose this makes more sense in C, which uses # null to terminate the strings, but it's inconvenient here... abbr_vals = {} abbr_chars = fobj.read(charcnt) def get_abbr(idx): # Gets a string starting at idx and running until the next \x00 # # We cannot pre-populate abbr_vals by splitting on \x00 because there # are some zones that use subsets of longer abbreviations, like so: # # LMT\x00AHST\x00HDT\x00 # # Where the idx to abbr mapping should be: # # {0: "LMT", 4: "AHST", 5: "HST", 9: "HDT"} if idx not in abbr_vals: span_end = abbr_chars.find(b"\x00", idx) abbr_vals[idx] = abbr_chars[idx:span_end].decode() return abbr_vals[idx] abbr = tuple(get_abbr(idx) for idx in abbrind) # The remainder of the file consists of leap seconds (currently unused) and # the standard/wall and ut/local indicators, which are metadata we don't need. # In version 2 files, we need to skip the unnecessary data to get at the TZ string, # and in version 1 files we'll just hopefully consume the rest of the file. # Each leap second record has size (time_size + 4) skip_bytes = ( header.isutcnt + header.isstdcnt + header.leapcnt * (time_size + 4) ) fobj.seek(skip_bytes, 1) if header.version >= 2: c = fobj.read(1) # Should be \n if c != b"\n": raise ValueError("Invalid TZif file: expected newline, got %r" % c) line = fobj.readline() if not line.endswith(b"\n"): raise ValueError("Invalid TZif file: unexpected end of file") tz_str = line.rstrip(b"\n") else: tz_str = None return trans_idx, trans_list_utc, utcoff, isdst, abbr, tz_str # How close in time (in seconds) the DST periods that _utcoff_to_dstoff uses # to choose between two possible DST offsets have to be _DST_CONSENSUS_WINDOW = 10 * 365 * 86400 class _TZifHeader: __slots__ = [ "version", "isutcnt", "isstdcnt", "leapcnt", "timecnt", "typecnt", "charcnt", ] def __init__(self, *args): assert len(self.__slots__) == len(args) for attr, val in zip(self.__slots__, args): setattr(self, attr, val) @classmethod def from_file(cls, stream): # The header starts with a 4-byte "magic" value if stream.read(4) != b"TZif": raise ValueError("Invalid TZif file: magic not found") _version = stream.read(1) if _version == b"\x00": version = 1 else: version = int(_version) stream.read(15) args = (version,) # Slots are defined in the order that the bytes are arranged args = args + struct.unpack(">6l", stream.read(24)) return cls(*args) class _ttinfo: __slots__ = ["utcoff", "dstoff", "tzname"] def __init__(self, utcoff, dstoff, tzname): self.utcoff = utcoff self.dstoff = dstoff self.tzname = tzname def __eq__(self, other): if not isinstance(other, _ttinfo): return NotImplemented return ( self.utcoff == other.utcoff and self.dstoff == other.dstoff and self.tzname == other.tzname ) def __repr__(self): # pragma: nocover return "%s(%s, %s, %s)" % ( self.__class__.__name__, self.utcoff, self.dstoff, self.tzname, ) _NO_TTINFO = _ttinfo(None, None, None) def _parse_tz_str(tz_str): # The tz string has the format: # # std[offset[dst[offset],start[/time],end[/time]]] # # std and dst must be 3 or more characters long and must not contain # a leading colon, embedded digits, commas, nor a plus or minus signs; # The spaces between "std" and "offset" are only for display and are # not actually present in the string. # # The format of the offset is ``[+|-]hh[:mm[:ss]]`` offset_str, *start_end_str = tz_str.split(",", 1) parser_re = ( r"(?P[a-zA-Z]+|<[a-zA-Z0-9+-]+>)" r"(?:" r"(?P[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?)" r"(?:" r"(?P[a-zA-Z]+|<[a-zA-Z0-9+-]+>)" r"(?P[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?)?" r")?" # dst r")?" # stdoff ) m = re.fullmatch(parser_re, offset_str, re.ASCII) if m is None: raise ValueError("%s is not a valid TZ string" % tz_str) std_abbr = m.group("std") dst_abbr = m.group("dst") dst_offset = None std_abbr = std_abbr.strip("<>") if dst_abbr: dst_abbr = dst_abbr.strip("<>") std_offset = m.group("stdoff") if std_offset: try: std_offset = _parse_tz_delta(std_offset) except ValueError as e: raise ValueError("Invalid STD offset in %s" % tz_str) else: # The STD offset is required raise ValueError("Invalid STD offset in %s" % tz_str) if dst_abbr is not None: dst_offset = m.group("dstoff") if dst_offset: try: dst_offset = _parse_tz_delta(dst_offset) except ValueError as e: raise ValueError("Invalid DST offset in %s" % tz_str) else: dst_offset = std_offset + 3600 if not start_end_str: raise ValueError("Missing transition rules: %s" % tz_str) start_end_strs = start_end_str[0].split(",", 1) try: start, end = (_parse_dst_start_end(x) for x in start_end_strs) except ValueError as e: raise ValueError("Invalid TZ string: %s" % tz_str) return _TZStr(std_abbr, std_offset, dst_abbr, dst_offset, start, end) elif start_end_str: raise ValueError("Transition rule present without DST: %s" % tz_str) else: # This is a static ttinfo, don't return _TZStr return _ttinfo( _load_timedelta(std_offset), _load_timedelta(0), std_abbr ) def _parse_dst_start_end(dststr): date, *time = dststr.split("/", 1) date_type = date[:1] if date_type == "M": n_is_julian = False m = re.fullmatch(r"M(\d{1,2})\.(\d)\.(\d)", date, re.ASCII) if m is None: raise ValueError("Invalid dst start/end date: %s" % dststr) date_offset = tuple(map(int, m.groups())) offset = _CalendarOffset(*date_offset) else: if date_type == "J": n_is_julian = True date = date[1:] else: n_is_julian = False if re.fullmatch(r"\d{1,3}", date, re.ASCII) is None: raise ValueError("Invalid dst start/end date: %s" % dststr) doy = int(date) offset = _DayOffset(doy, n_is_julian) if time: offset.hour, offset.minute, offset.second = _parse_transition_time( time[0] ) return offset def _parse_transition_time(time_str): match = re.fullmatch( r"(?P[+-])?(?P\d{1,3})(:(?P\d{2})(:(?P\d{2}))?)?", time_str, re.ASCII, ) if match is None: raise ValueError("Invalid time: %s" % time_str) h, m, s = (int(v or 0) for v in map(match.group, ("h", "m", "s"))) if h > 167: raise ValueError("Hour must be in [0, 167]: %s" % time_str) if match.group("sign") == "-": h, m, s = -h, -m, -s return h, m, s def _parse_tz_delta(tz_delta): match = re.fullmatch( r"(?P[+-])?(?P\d{1,3})(:(?P\d{2})(:(?P\d{2}))?)?", tz_delta, re.ASCII, ) # Anything passed to this function should already have hit an equivalent # regular expression to find the section to parse. assert match is not None, tz_delta h, m, s = (int(v or 0) for v in map(match.group, ("h", "m", "s"))) total = h * 3600 + m * 60 + s if h > 24: raise ValueError("Offset hours must be in [0, 24]: %s" % tz_delta) # Yes, +5 maps to an offset of -5h if match.group("sign") != "-": total *= -1 return total class _TZStr: __slots__ = ( "std", "dst", "start", "end", "get_trans_info", "get_trans_info_fromutc", "dst_diff", ) def __init__( self, std_abbr, std_offset, dst_abbr, dst_offset, start=None, end=None ): self.dst_diff = dst_offset - std_offset std_offset = _load_timedelta(std_offset) self.std = _ttinfo( utcoff=std_offset, dstoff=_load_timedelta(0), tzname=std_abbr ) self.start = start self.end = end dst_offset = _load_timedelta(dst_offset) delta = _load_timedelta(self.dst_diff) self.dst = _ttinfo(utcoff=dst_offset, dstoff=delta, tzname=dst_abbr) # These are assertions because the constructor should only be called # by functions that would fail before passing start or end assert start is not None, "No transition start specified" assert end is not None, "No transition end specified" self.get_trans_info = self._get_trans_info self.get_trans_info_fromutc = self._get_trans_info_fromutc def transitions(self, year): start = self.start.year_to_epoch(year) end = self.end.year_to_epoch(year) return start, end def _near_new_year(self, ts, year): """Whether ts is close enough to the new year that the rules for the previous or next year might matter.""" year_start = _post_epoch_days_before_year(year) * 86400 year_end = _post_epoch_days_before_year(year + 1) * 86400 return ( ts < year_start + _NEW_YEAR_MARGIN or ts >= year_end - _NEW_YEAR_MARGIN ) def _get_trans_info(self, ts, year, fold): """Get the information about the current transition - tti""" if self._near_new_year(ts, year): return self._get_trans_info_near_new_year(ts, fold) start, end = self.transitions(year) # With fold = 0, the period (denominated in local time) with the # smaller offset starts at the end of the gap and ends at the end of # the fold; with fold = 1, it runs from the start of the gap to the # beginning of the fold. # # So in order to determine the DST boundaries we need to know both # the fold and whether DST is positive or negative (rare), and it # turns out that this boils down to fold XOR is_positive. if fold == (self.dst_diff >= 0): end -= self.dst_diff else: start += self.dst_diff if start < end: isdst = start <= ts < end else: isdst = not (end <= ts < start) return self.dst if isdst else self.std def _get_trans_info_near_new_year(self, ts, fold): # Answer the question in terms of UTC, where the transitions from the # adjacent years are taken into account: a local time is valid for # an offset if the rules give that offset at the corresponding UTC # time. valid = [] for tti in (self.std, self.dst): utc_ts = ts - tti.utcoff.total_seconds() try: utc_year = (EPOCH + timedelta(seconds=utc_ts)).year except OverflowError: # Before year 1 or after year 9999 utc_year = MINYEAR if utc_ts < 0 else MAXYEAR actual, _ = self._get_trans_info_fromutc_near_new_year( utc_ts, utc_year ) if actual is tti: valid.append(tti) if len(valid) == 1: return valid[0] smaller, larger = sorted((self.std, self.dst), key=lambda t: t.utcoff) if valid: # Ambiguous: fold=0 is the first occurrence, with the larger offset return larger if fold == 0 else smaller else: # Imaginary: fold=0 uses the offset from before the transition return smaller if fold == 0 else larger def _get_trans_info_fromutc_near_new_year(self, ts, year): # The rules are in terms of the local year, which near the new year # is not always the UTC year, and a rule can put a transition up to a # week into the previous or next year (e.g. "J365/25"), so look at the # transitions for the years on either side as well and use the last # one before ts. std_utcoff = self.std.utcoff.total_seconds() dst_utcoff = self.dst.utcoff.total_seconds() transitions = [] for y in (year - 1, year, year + 1): start, end = self.transitions(y) transitions.append((start - std_utcoff, True)) transitions.append((end - dst_utcoff, False)) # When one DST period ends at the same instant as the next one starts, # as with "DST all year" rules like "0/0,J365/25", sorting puts the # end first, so these stay in DST without a transition in between. transitions.sort() isdst = not transitions[0][1] last_change = None i = 0 while i < len(transitions) and transitions[i][0] <= ts: trans_ts = transitions[i][0] new_isdst = isdst while i < len(transitions) and transitions[i][0] == trans_ts: new_isdst = transitions[i][1] i += 1 if new_isdst != isdst: isdst = new_isdst last_change = trans_ts if isdst: tti, tti_prev = self.dst, self.std else: tti, tti_prev = self.std, self.dst # A transition to a smaller offset creates a fold just after it. fold = False if last_change is not None: shift = (tti_prev.utcoff - tti.utcoff).total_seconds() fold = shift > ts - last_change return (tti, fold) def _get_trans_info_fromutc(self, ts, year): if self._near_new_year(ts, year): return self._get_trans_info_fromutc_near_new_year(ts, year) start, end = self.transitions(year) start -= self.std.utcoff.total_seconds() end -= self.dst.utcoff.total_seconds() if start < end: isdst = start <= ts < end else: isdst = not (end <= ts < start) # For positive DST, the ambiguous period is one dst_diff after the end # of DST; for negative DST, the ambiguous period is one dst_diff before # the start of DST. if self.dst_diff > 0: ambig_start = end ambig_end = end + self.dst_diff else: ambig_start = start ambig_end = start - self.dst_diff fold = ambig_start <= ts < ambig_end return (self.dst if isdst else self.std, fold) # A rule can put a transition up to 167 hours (just under a week) away from # the day it names, and local time is at most a day or so away from UTC, so # only times within this distance of the new year can be affected by the # rules for the previous or next year. _NEW_YEAR_MARGIN = 10 * 86400 def _post_epoch_days_before_year(year): """Get the number of days between 1970-01-01 and YEAR-01-01""" y = year - 1 return y * 365 + y // 4 - y // 100 + y // 400 + 1 - EPOCHORDINAL class _DayOffset: __slots__ = ["d", "julian", "hour", "minute", "second"] def __init__(self, d, julian, hour=2, minute=0, second=0): min_day = 0 + julian # convert bool to int if not min_day <= d <= 365: raise ValueError("d must be in [%s, 365], not: %s" % (min_day, d)) self.d = d self.julian = julian self.hour = hour self.minute = minute self.second = second def year_to_epoch(self, year): days_before_year = _post_epoch_days_before_year(year) # "n" counts days from 0 and includes February 29; "Jn" counts days # from 1 and never counts February 29, so in leap years, J60 (March 1) # and every day after it is one day later than its number suggests. d = self.d if self.julian: d -= 1 if d >= 59 and calendar.isleap(year): d += 1 epoch = (days_before_year + d) * 86400 epoch += self.hour * 3600 + self.minute * 60 + self.second return epoch class _CalendarOffset: __slots__ = ["m", "w", "d", "hour", "minute", "second"] _DAYS_BEFORE_MONTH = ( -1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, ) def __init__(self, m, w, d, hour=2, minute=0, second=0): if not 1 <= m <= 12: raise ValueError("m must be in [1, 12]") if not 1 <= w <= 5: raise ValueError("w must be in [1, 5]") if not 0 <= d <= 6: raise ValueError("d must be in [0, 6]") self.m = m self.w = w self.d = d self.hour = hour self.minute = minute self.second = second @classmethod def _ymd2ord(cls, year, month, day): return ( _post_epoch_days_before_year(year) + cls._DAYS_BEFORE_MONTH[month] + (month > 2 and calendar.isleap(year)) + day - 1 ) # TODO: These are not actually epoch dates as they are expressed in local time def year_to_epoch(self, year): """Calculates the datetime of the occurrence from the year""" # We know year and month, we need to convert w, d into day of month # # Week 1 is the first week in which day `d` (where 0 = Sunday) appears. # Week 5 represents the last occurrence of day `d`, so we need to know # the range of the month. # # This doesn't use calendar.monthrange because the rules for years 0 # and 10000 can affect times that datetime can represent, and # calendar.monthrange constructs a datetime.date. Instead, get the # weekday (0 = Monday) from the ordinal: 1970-01-01 was a Thursday. first_ordinal = self._ymd2ord(year, self.m, 1) first_day = (first_ordinal + 3) % 7 if self.m == 12: next_ordinal = self._ymd2ord(year + 1, 1, 1) else: next_ordinal = self._ymd2ord(year, self.m + 1, 1) days_in_month = next_ordinal - first_ordinal # This equation seems magical, so I'll break it down: # 1. calendar says 0 = Monday, POSIX says 0 = Sunday # so we need first_day + 1 to get 1 = Monday -> 7 = Sunday, # which is still equivalent because this math is mod 7 # 2. Get first day - desired day mod 7: -1 % 7 = 6, so we don't need # to do anything to adjust negative numbers. # 3. Add 1 because month days are a 1-based index. month_day = (self.d - (first_day + 1)) % 7 + 1 # Now use a 0-based index version of `w` to calculate the w-th # occurrence of `d` month_day += (self.w - 1) * 7 # month_day will only be > days_in_month if w was 5, and `w` means # "last occurrence of `d`", so now we just check if we over-shot the # end of the month and if so knock off 1 week. if month_day > days_in_month: month_day -= 7 ordinal = self._ymd2ord(year, self.m, month_day) epoch = ordinal * 86400 epoch += self.hour * 3600 + self.minute * 60 + self.second return epoch python_dateutil-4.0.0/src/dateutil/tz/_tzpath.py0000644000000000000000000000047013615410400016732 0ustar00import zoneinfo reset_tzpath = zoneinfo.reset_tzpath InvalidTZPathWarning = zoneinfo.InvalidTZPathWarning def __getattr__(name): if name == "TZPATH": return zoneinfo.TZPATH else: raise AttributeError( "Module %s has no attribute %s" % (repr(__name__), repr(name)) ) python_dateutil-4.0.0/src/dateutil/tz/tz.py0000644000000000000000000013611413615410400015723 0ustar00""" This module offers timezone implementations subclassing the abstract :py:class:`datetime.tzinfo` type. There are classes to handle tzfile format files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, etc), TZ environment string (in all known formats), given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, and UTC timezone. """ import _thread import contextlib import datetime import os import time import warnings import weakref from collections import OrderedDict from .. import _tzdata_impl from . import _tzpath from ._common import _tzinfo, _validate_fromutc_inputs, enfold, tzrangebase from ._factories import _TzOffsetFactory, _TzSingleton, _TzStrFactory from ._tzfile import tzfile try: from .win import tzwin, tzwinlocal except ImportError: tzwin = tzwinlocal = None ZERO = datetime.timedelta(0) EPOCH = datetime.datetime(1970, 1, 1, 0, 0) class tzutc(datetime.tzinfo, metaclass=_TzSingleton): """ This is a tzinfo object that represents the UTC time zone. **Examples:** .. doctest:: >>> from datetime import * >>> from dateutil.tz import * >>> datetime.now() datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) >>> datetime.now(tzutc()) datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) >>> datetime.now(tzutc()).tzname() 'UTC' .. versionchanged:: 2.7.0 ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will always return the same object. .. doctest:: >>> from dateutil.tz import tzutc, UTC >>> tzutc() is tzutc() True >>> tzutc() is UTC True """ def utcoffset(self, dt): return ZERO def dst(self, dt): return ZERO def tzname(self, dt): return "UTC" def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ return False @_validate_fromutc_inputs def fromutc(self, dt): """ Fast track version of fromutc() returns the original ``dt`` object for any valid :py:class:`datetime.datetime` object. """ return dt def __eq__(self, other): if not isinstance(other, (tzutc, tzoffset)): return NotImplemented return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset == ZERO)) __hash__ = None def __repr__(self): return "%s()" % self.__class__.__name__ def __reduce__(self): return (self.__class__, tuple()) #: Convenience constant providing a :class:`tzutc()` instance #: #: .. versionadded:: 2.7.0 UTC = tzutc() class tzoffset(datetime.tzinfo, metaclass=_TzOffsetFactory): """ A simple class for representing a fixed offset from UTC. :param name: The timezone name, to be returned when ``tzname()`` is called. :param offset: The time zone offset in seconds, or (since version 2.6.0, represented as a :py:class:`datetime.timedelta` object). """ def __init__(self, name, offset): self._name = name try: # Allow a timedelta offset = offset.total_seconds() except (TypeError, AttributeError): pass self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def dst(self, dt): return ZERO def tzname(self, dt): return self._name @_validate_fromutc_inputs def fromutc(self, dt): return dt + self._offset def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ return False def __eq__(self, other): if not isinstance(other, tzoffset): return NotImplemented return self._offset == other._offset __hash__ = None def __repr__(self): return "%s(%s, %s)" % (self.__class__.__name__, repr(self._name), int(self._offset.total_seconds())) def __reduce__(self): return (self.__class__, (self._name, self._offset)) class tzlocal(_tzinfo): """ A :class:`tzinfo` subclass built around the ``time`` timezone functions. """ def __init__(self): super().__init__() self._std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: self._dst_offset = datetime.timedelta(seconds=-time.altzone) else: self._dst_offset = self._std_offset self._dst_saved = self._dst_offset - self._std_offset self._hasdst = bool(self._dst_saved) self._tznames = tuple(time.tzname) def utcoffset(self, dt): if dt is None and self._hasdst: return None if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt): if dt is None and self._hasdst: return None if self._isdst(dt): return self._dst_offset - self._std_offset else: return ZERO def tzname(self, dt): return self._tznames[self._isdst(dt)] def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ naive_dst = self._naive_is_dst(dt) return (not naive_dst and (naive_dst != self._naive_is_dst(dt - self._dst_saved))) def _naive_is_dst(self, dt): timestamp = _datetime_to_timestamp(dt) return time.localtime(timestamp + time.timezone).tm_isdst def _isdst(self, dt, fold_naive=True): # We can't use mktime here. It is unstable when deciding if # the hour near to a change is DST or not. # # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # # The code above yields the following result: # # >>> import tz, datetime # >>> t = tz.tzlocal() # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRDT' # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() # 'BRST' # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRST' # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() # 'BRDT' # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRDT' # # Here is a more stable implementation: # if not self._hasdst: return False # Check for ambiguous times: dstval = self._naive_is_dst(dt) if self.is_ambiguous(dt): return not dt.fold return dstval def __eq__(self, other): if isinstance(other, tzlocal): return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset) elif isinstance(other, tzutc): return (not self._hasdst and self._tznames[0] in {'UTC', 'GMT'} and self._std_offset == ZERO) elif isinstance(other, tzoffset): return (not self._hasdst and self._tznames[0] == other._name and self._std_offset == other._offset) else: return NotImplemented __hash__ = None def __repr__(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzrange(tzrangebase): """ The ``tzrange`` object is a time zone specified by a set of offsets and abbreviations, equivalent to the way the ``TZ`` variable can be specified in POSIX-like systems, but using Python delta objects to specify DST start, end and offsets. :param stdabbr: The abbreviation for standard time (e.g. ``'EST'``). :param stdoffset: An integer or :class:`datetime.timedelta` object or equivalent specifying the base offset from UTC. If unspecified, +00:00 is used. :param dstabbr: The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). If specified, with no other DST information, DST is assumed to occur and the default behavior or ``dstoffset``, ``start`` and ``end`` is used. If unspecified and no other DST information is specified, it is assumed that this zone has no DST. If this is unspecified and other DST information is *is* specified, DST occurs in the zone but the time zone abbreviation is left unchanged. :param dstoffset: A an integer or :class:`datetime.timedelta` object or equivalent specifying the UTC offset during DST. If unspecified and any other DST information is specified, it is assumed to be the STD offset +1 hour. :param start: A :class:`relativedelta.relativedelta` object or equivalent specifying the time and time of year that daylight savings time starts. To specify, for example, that DST starts at 2AM on the 2nd Sunday in March, pass: ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` If unspecified and any other DST information is specified, the default value is 2 AM on the first Sunday in April. :param end: A :class:`relativedelta.relativedelta` object or equivalent representing the time and time of year that daylight savings time ends, with the same specification method as in ``start``. One note is that this should point to the first time in the *standard* zone, so if a transition occurs at 2AM in the DST zone and the clocks are set back 1 hour to 1AM, set the ``hours`` parameter to +1. **Examples:** .. testsetup:: tzrange from dateutil.tz import tzrange, tzstr .. doctest:: tzrange >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") True >>> from dateutil.relativedelta import * >>> range1 = tzrange("EST", -18000, "EDT") >>> range2 = tzrange("EST", -18000, "EDT", -14400, ... relativedelta(hours=+2, month=4, day=1, ... weekday=SU(+1)), ... relativedelta(hours=+1, month=10, day=31, ... weekday=SU(-1))) >>> tzstr('EST5EDT') == range1 == range2 True """ def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta from dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr try: stdoffset = stdoffset.total_seconds() except (TypeError, AttributeError): pass try: dstoffset = dstoffset.total_seconds() except (TypeError, AttributeError): pass if stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not None: self._dst_offset = self._std_offset + datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr and start is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr and end is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end self._dst_base_offset_ = self._dst_offset - self._std_offset self.hasdst = bool(self._start_delta) def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones. """ if not self.hasdst: return None base_year = datetime.datetime(year, 1, 1) start = base_year + self._start_delta end = base_year + self._end_delta return (start, end) def __eq__(self, other): if not isinstance(other, tzrange): return NotImplemented return (self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._start_delta == other._start_delta and self._end_delta == other._end_delta) @property def _dst_base_offset(self): return self._dst_base_offset_ class tzstr(tzrange, metaclass=_TzStrFactory): """ ``tzstr`` objects are time zone objects specified by a time-zone string as it would be passed to a ``TZ`` variable on POSIX-style systems (see the `GNU C Library: TZ Variable`_ for more details). There is one notable exception, which is that POSIX-style time zones use an inverted offset format, so normally ``GMT+3`` would be parsed as an offset 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX behavior, pass a ``True`` value to ``posix_offset``. The :class:`tzrange` object provides the same functionality, but is specified using :class:`relativedelta.relativedelta` objects. rather than strings. :param s: A time zone string in ``TZ`` variable format. This can be a :class:`bytes`, :class:`str` or a stream emitting Unicode characters (e.g. :class:`StringIO`). :param posix_offset: Optional. If set to ``True``, interpret strings such as ``GMT+3`` or ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the POSIX standard. .. caution:: Prior to version 2.7.0, this function also supported time zones in the format: * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` This format is non-standard and has been deprecated; this function will raise a :class:`DeprecatedTZFormatWarning` until support is removed in a future version. .. _`GNU C Library: TZ Variable`: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html """ def __init__(self, s, posix_offset=False): global parser from dateutil.parser import _parser as parser self._s = s res = parser._parsetz(s) if res is None or res.any_unused_tokens: raise ValueError("unknown string format") # Here we break the compatibility with the TZ variable handling. # GMT-3 actually *means* the timezone -3. if res.stdabbr in ("GMT", "UTC") and not posix_offset: res.stdoffset *= -1 # We must initialize it first, since _delta() needs # _std_offset and _dst_offset set. Use False in start/end # to avoid building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta = None self._end_delta = None else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1) self.hasdst = bool(self._start_delta) def _delta(self, x, isend=0): from dateutil import relativedelta kwargs = {} if x.month is not None: kwargs["month"] = x.month if x.weekday is not None: kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs["day"] = 1 else: kwargs["day"] = 31 elif x.day: kwargs["day"] = x.day elif x.yday is not None: kwargs["yearday"] = x.yday elif x.jyday is not None: kwargs["nlyearday"] = x.jyday if not kwargs: # Default is to start on first sunday of april, and end # on last sunday of october. if not isend: kwargs["month"] = 4 kwargs["day"] = 1 kwargs["weekday"] = relativedelta.SU(+1) else: kwargs["month"] = 10 kwargs["day"] = 31 kwargs["weekday"] = relativedelta.SU(-1) if x.time is not None: kwargs["seconds"] = x.time else: # Default is 2AM. kwargs["seconds"] = 7200 if isend: # Convert to standard time, to follow the documented way # of working with the extra hour. See the documentation # of the tzinfo class. delta = self._dst_offset - self._std_offset kwargs["seconds"] -= delta.seconds + delta.days * 86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp: def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule = rrule class _tzicalvtz(_tzinfo): def __init__(self, tzid, comps=[]): super().__init__() self._tzid = tzid self._comps = comps self._cachedate = [] self._cachecomp = [] self._cache_lock = _thread.allocate_lock() def _find_comp(self, dt): if len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None) try: with self._cache_lock: return self._cachecomp[self._cachedate.index((dt, dt.fold))] except ValueError: pass lastcompdt = None lastcomp = None for comp in self._comps: compdt = self._find_compdt(comp, dt) if compdt and (not lastcompdt or lastcompdt < compdt): lastcompdt = compdt lastcomp = comp if not lastcomp: # RFC says nothing about what to do when a given # time is before the first onset date. We'll look for the # first standard component, or the first component, if # none is found. for comp in self._comps: if not comp.isdst: lastcomp = comp break else: lastcomp = comp[0] with self._cache_lock: self._cachedate.insert(0, (dt, dt.fold)) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def _find_compdt(self, comp, dt): if comp.tzoffsetdiff < ZERO and dt.fold: dt -= comp.tzoffsetdiff compdt = comp.rrule.before(dt, inc=True) return compdt def utcoffset(self, dt): if dt is None: return None return self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return ZERO def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return "" % repr(self._tzid) __reduce__ = object.__reduce__ class tzical: """ This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. :param `fileobj`: A file or stream in iCalendar format, which should be UTF-8 encoded with CRLF endings. .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 """ def __init__(self, fileobj): global rrule from dateutil import rrule if isinstance(fileobj, str): self._s = fileobj # ical should be encoded in UTF-8 with CRLF fileobj = open(fileobj, 'r') else: self._s = getattr(fileobj, 'name', repr(fileobj)) fileobj = contextlib.nullcontext(fileobj) self._vtz = {} with fileobj as fobj: self._parse_rfc(fobj.read()) def keys(self): """ Retrieves the available time zones as a list. """ return list(self._vtz.keys()) def get(self, tzid=None): """ Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. :param tzid: If there is exactly one time zone available, omitting ``tzid`` or passing :py:const:`None` value returns it. Otherwise a valid key (which can be retrieved from :func:`keys`) is required. :raises ValueError: Raised if ``tzid`` is not specified but there are either more or fewer than 1 zone defined. :returns: Returns either a :py:class:`datetime.tzinfo` object representing the relevant time zone or :py:const:`None` if the ``tzid`` was not found. """ if tzid is None: if len(self._vtz) == 0: raise ValueError("no timezones defined") elif len(self._vtz) > 1: raise ValueError("more than one timezone available") tzid = next(iter(self._vtz)) return self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip() if not s: raise ValueError("empty offset") if s[0] in ('+', '-'): signal = (-1, +1)[s[0] == '+'] s = s[1:] else: signal = +1 if not (s.isascii() and s.isdigit()): raise ValueError("invalid offset: " + s) if len(s) == 4: return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal elif len(s) == 6: return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal else: raise ValueError("invalid offset: " + s) def _parse_rfc(self, s): lines = s.splitlines() if not lines: raise ValueError("empty string") # Unfold i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 tzid = None comps = [] invtz = False comptype = None for line in lines: if not line: continue name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError("empty property name") name = parms[0].upper() parms = parms[1:] if invtz: if name == "BEGIN": if value in ("STANDARD", "DAYLIGHT"): # Process component pass else: raise ValueError("unknown component: "+value) comptype = value founddtstart = False tzoffsetfrom = None tzoffsetto = None rrulelines = [] tzname = None elif name == "END": if value == "VTIMEZONE": if comptype: raise ValueError("component not closed: "+comptype) if not tzid: raise ValueError("mandatory TZID not found") if not comps: raise ValueError( "at least one component is needed") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif value == comptype: if not founddtstart: raise ValueError("mandatory DTSTART not found") if tzoffsetfrom is None: raise ValueError( "mandatory TZOFFSETFROM not found") if tzoffsetto is None: raise ValueError( "mandatory TZOFFSETFROM not found") # Process component rr = None if rrulelines: rr = rrule.rrulestr("\n".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == "DAYLIGHT"), tzname, rr) comps.append(comp) comptype = None else: raise ValueError("invalid component end: "+value) elif comptype: if name == "DTSTART": # DTSTART in VTIMEZONE takes a subset of valid RRULE # values under RFC 5545. for parm in parms: if parm != 'VALUE=DATE-TIME': msg = ('Unsupported DTSTART param in ' + 'VTIMEZONE: ' + parm) raise ValueError(msg) rrulelines.append(line) founddtstart = True elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): rrulelines.append(line) elif name == "TZOFFSETFROM": if parms: raise ValueError( "unsupported %s parm: %s " % (name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name == "TZOFFSETTO": if parms: raise ValueError( "unsupported TZOFFSETTO parm: "+parms[0]) tzoffsetto = self._parse_offset(value) elif name == "TZNAME": if parms: raise ValueError( "unsupported TZNAME parm: "+parms[0]) tzname = value elif name == "COMMENT": pass else: raise ValueError("unsupported property: "+name) else: if name == "TZID": if parms: raise ValueError( "unsupported TZID parm: "+parms[0]) tzid = value elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): pass else: raise ValueError("unsupported property: "+name) elif name == "BEGIN" and value == "VTIMEZONE": tzid = None comps = [] invtz = True def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._s)) TZFILES = ["/etc/localtime", "localtime"] def __get_gettz(): tzlocal_classes = (tzlocal,) if tzwinlocal is not None: tzlocal_classes += (tzwinlocal,) class GettzFunc: """ Retrieve a time zone object from a string representation This function is intended to retrieve the :py:class:`tzinfo` subclass that best represents the time zone that would be used if a POSIX `TZ variable`_ were set to the same value. If no argument or an empty string is passed to ``gettz``, local time is returned: .. code-block:: python3 >>> gettz() tzfile('/etc/localtime') This function is also the preferred way to map IANA tz database keys to :class:`tzfile` objects. It searches for these keys in the following order: 1. On the search path defined in :data:`TZPATH`. 2. In the `tzdata `_ Python package. 3. Using the system-specific mechanisms (e.g. the Windows registry). .. code-block:: python3 >>> gettz('Pacific/Kiritimati') tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') On Windows, the standard is extended to include the Windows-specific zone names provided by the operating system: .. code-block:: python3 >>> gettz('Egypt Standard Time') tzwin('Egypt Standard Time') Passing a GNU ``TZ`` style string time zone specification returns a :class:`tzstr` object: .. code-block:: python3 >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') :param name: A time zone name (IANA, or, on Windows, Windows keys), location of a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone specifier. An empty string, no argument or ``None`` is interpreted as local time. :return: Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` subclasses. .. versionchanged:: 2.7.0 After version 2.7.0, any two calls to ``gettz`` using the same input strings will return the same object: .. code-block:: python3 >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') True In addition to improving performance, this ensures that `"same zone" semantics`_ are used for datetimes in the same zone. .. _`TZ variable`: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html .. _`"same zone" semantics`: https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html """ def __init__(self): self.__instances = weakref.WeakValueDictionary() self.__strong_cache_size = 8 self.__strong_cache = OrderedDict() self._cache_lock = _thread.allocate_lock() def __call__(self, name=None): with self._cache_lock: rv = self.__instances.get(name, None) if rv is None: # TODO: This holds the cache lock while nocache() reads # the file, so a slow lookup (e.g. walking TZPATH on a # network file system) blocks every other gettz call, # including cache hits for unrelated keys. rv = self.nocache(name=name) if not (name is None or isinstance(rv, tzlocal_classes) or rv is None): # tzlocal is slightly more complicated than the other # time zone providers because it depends on environment # at construction time, so don't cache that. # # We also cannot store weak references to None, so we # will also not store that. self.__instances[name] = rv else: # No need for strong caching, return immediately return rv self.__strong_cache[name] = self.__strong_cache.pop(name, rv) if len(self.__strong_cache) > self.__strong_cache_size: self.__strong_cache.popitem(last=False) return rv def set_cache_size(self, size): with self._cache_lock: self.__strong_cache_size = size while len(self.__strong_cache) > size: self.__strong_cache.popitem(last=False) def cache_clear(self): with self._cache_lock: self.__instances = weakref.WeakValueDictionary() self.__strong_cache.clear() @staticmethod def nocache(name=None): """A non-cached version of gettz""" tz = None if not name: try: name = os.environ["TZ"] except KeyError: pass if name is None or name in ("", ":"): for filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath for path in _tzpath.TZPATH: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break except (OSError, ValueError): pass else: tz = tzlocal() else: try: if name.startswith(":"): name = name[1:] except TypeError as e: if isinstance(name, bytes): new_msg = "gettz argument should be str, not bytes" raise TypeError(new_msg) from e else: raise # A NUL byte can never be part of a key or a path, and # depending on the platform and Python version it raises # ValueError from os.path, winreg or open(), so reject it # up front rather than catching it in every branch. if "\x00" in name: return None if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz = None else: if _escapes_tzpath(name): _warn_tzpath_escape(name) for path in _tzpath.TZPATH: filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if not os.path.isfile(filepath): continue try: tz = tzfile(filepath, key=name) break except (OSError, ValueError): # TODO: A file that exists but can't be read or # isn't a valid TZif file is silently skipped, # and the key is looked up in the next TZPATH # entry and then in tzdata. Consider warning # here, since this usually means the system time # zone data is broken. pass else: tz = None # As with the search path lookup above, also try # the name with spaces replaced by underscores. candidates = [name] if " " in name: candidates.append(name.replace(" ", "_")) for candidate in candidates: try: with _tzdata_impl._load_tzdata(candidate) as f: return tzfile(f, key=name) except ValueError: # TZFileNotFound is a ValueError, and so is # the error raised for files in tzdata that # are not TZif files (e.g. "zone.tab"), # which are skipped just as on TZPATH. pass if tzwin is not None: try: tz = tzwin(name) except OSError: tz = None if not tz: for c in name: # name is not a tzstr unless it has at least # one offset. For short values of "name", an # explicit for loop seems to be the fastest way # To determine if a string contains a digit if c in "0123456789": try: tz = tzstr(name) except ValueError: pass break else: if name in ("GMT", "UTC"): tz = UTC elif name in time.tzname: tz = tzlocal() return tz return GettzFunc() gettz = __get_gettz() del __get_gettz class DeprecatedTzKeyWarning(FutureWarning): """Warning raised when :func:`gettz` is given a key outside of TZPATH. Relative keys like ``"../../etc/localtime"`` resolve to files outside of every directory on :data:`TZPATH`. Support for these is deprecated, and a warnings filter turns this warning into an error by default. To keep the old behavior for now, filter it out, e.g.:: warnings.filterwarnings( "ignore", category=dateutil.tz.DeprecatedTzKeyWarning ) Absolute paths to TZif files are not affected. """ def _escapes_tzpath(name): # A relative key stays inside every TZPATH entry unless, once normalized # (which also turns os.altsep into os.sep), it starts by going up a # directory. return os.path.normpath(name).split(os.sep, 1)[0] == os.pardir def _warn_tzpath_escape(name): # As in dateutil.zoneinfo.rebuild, the filter is appended at call time, # so any filter the user has installed for this category wins. warnings.filterwarnings( "error", category=DeprecatedTzKeyWarning, append=True ) warnings.warn( "gettz(%r) refers to a file outside of TZPATH; support for keys " "like this is deprecated and will be removed in a future version. " "Use an absolute path instead." % (name,), DeprecatedTzKeyWarning, stacklevel=4, ) def available_iana_timezones(): """Returns a set containing all available IANA time zones keys. These are suitable for use with :func:`gettz`. This is essentially a direct port of :py:func:`zoneinfo.available_timezones`. The search includes time zones found on :data:`TZPATH` as well as any time zones provided by the `tzdata `_ package if it is installed. :return: Returns a mutable set containing strings of time zones. Each call will return a fresh set. .. caution:: This may attempt to open a large number of files, since the best way to determine if a given file on the time zone search path is to open it and check for the "magic string" at the beginning. .. note:: These values are not designed to be exposed to end-users; for user-facing elements, applications should use something like CLDR (the Unicode Common Locale Data Repository) to get more user-friendly strings. """ # Start with loading from the tzdata package if it exists: this has a # pre-assembled list of zones that only requires opening one file. try: valid_zones = set(_tzdata_impl._load_tzdata_keys()) except ImportError: valid_zones = set() def valid_key(fpath): try: with open(fpath, "rb") as f: return f.read(4) == b"TZif" except Exception: # pragma: nocover return False for tz_root in _tzpath.TZPATH: if not os.path.exists(tz_root): continue for root, dirnames, files in os.walk(tz_root): if root == tz_root: # right/ and posix/ are special directories and shouldn't be # included in the output of available zones if "right" in dirnames: dirnames.remove("right") if "posix" in dirnames: dirnames.remove("posix") for file in files: fpath = os.path.join(root, file) key = os.path.relpath(fpath, start=tz_root) if os.sep != "/": # pragma: nocover key = key.replace(os.sep, "/") if not key or key in valid_zones: continue if valid_key(fpath): valid_zones.add(key) if "posixrules" in valid_zones: # posixrules is a special symlink-only time zone where it exists, it # should not be included in the output valid_zones.remove("posixrules") if "localtime" in valid_zones: # localtime is a special symlink-only time zone where it exists, it # should not be included in the output valid_zones.remove("localtime") return valid_zones def datetime_exists(dt, tz=None): """ Given a datetime and a time zone, determine whether or not a given datetime would fall in a gap. :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" exists in ``tz``. .. versionadded:: 2.7.0 """ if tz is None: if dt.tzinfo is None: raise ValueError('Datetime is naive and no time zone provided.') tz = dt.tzinfo dt = dt.replace(tzinfo=None) # This is essentially a test of whether or not the datetime can survive # a round trip to UTC. dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz) dt_rt = dt_rt.replace(tzinfo=None) return dt == dt_rt def datetime_ambiguous(dt, tz=None): """ Given a datetime and a time zone, determine whether or not a given datetime is ambiguous (i.e if there are two times differentiated only by their DST status). :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" is ambiguous in ``tz``. .. versionadded:: 2.6.0 """ if tz is None: if dt.tzinfo is None: raise ValueError('Datetime is naive and no time zone provided.') tz = dt.tzinfo # If a time zone defines its own "is_ambiguous" function, we'll use that. is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) if is_ambiguous_fn is not None: try: return tz.is_ambiguous(dt) except Exception: pass # If it doesn't come out and tell us it's ambiguous, we'll just check if # the fold attribute has any effect on this particular date and time. dt = dt.replace(tzinfo=tz) wall_0 = enfold(dt, fold=0) wall_1 = enfold(dt, fold=1) same_offset = wall_0.utcoffset() == wall_1.utcoffset() same_dst = wall_0.dst() == wall_1.dst() return not (same_offset and same_dst) def resolve_imaginary(dt): """ Given a datetime that may be imaginary, return an existing datetime. This function assumes that an imaginary datetime represents what the wall time would be in a zone had the offset transition not occurred, so it will always fall forward by the transition's change in offset. .. doctest:: >>> from dateutil import tz >>> from datetime import datetime >>> NYC = tz.gettz('America/New_York') >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) 2017-03-12 03:30:00-04:00 >>> KIR = tz.gettz('Pacific/Kiritimati') >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) 1995-01-02 12:30:00+14:00 As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, existing datetime, so a round-trip to and from UTC is sufficient to get an extant datetime, however, this generally "falls back" to an earlier time rather than falling forward to the STD side (though no guarantees are made about this behavior). :param dt: A :class:`datetime.datetime` which may or may not exist. :return: Returns an existing :class:`datetime.datetime`. If ``dt`` was not imaginary, the datetime returned is guaranteed to be the same object passed to the function. .. versionadded:: 2.7.0 """ if dt.tzinfo is not None and not datetime_exists(dt): curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset() old_offset = (dt - datetime.timedelta(hours=24)).utcoffset() dt += curr_offset - old_offset return dt def _datetime_to_timestamp(dt): """ Convert a :class:`datetime.datetime` object to an epoch timestamp in seconds since January 1, 1970, ignoring the time zone. """ return (dt.replace(tzinfo=None) - EPOCH).total_seconds() # vim:ts=4:sw=4:et python_dateutil-4.0.0/src/dateutil/tz/win.py0000644000000000000000000003135213615410400016061 0ustar00""" This module provides an interface to the native time zone data on Windows, including :py:class:`datetime.tzinfo` implementations. Attempting to import this module on a non-Windows platform will raise an :py:obj:`ImportError`. """ # This code was originally contributed by Jeffrey Harris. import ctypes import datetime import os import struct import winreg from ctypes import wintypes from ._common import tzrangebase __all__ = ["tzwin", "tzwinlocal", "tzres"] ONEWEEK = datetime.timedelta(7) TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" def _settzkeyname(): handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: winreg.OpenKey(handle, TZKEYNAMENT).Close() TZKEYNAME = TZKEYNAMENT except OSError: TZKEYNAME = TZKEYNAME9X handle.Close() return TZKEYNAME TZKEYNAME = _settzkeyname() class tzres: """ Class for accessing ``tzres.dll``, which contains timezone name related resources. .. versionadded:: 2.5.0 """ p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char def __init__(self, tzres_loc='tzres.dll'): # Load the user32 DLL so we can load strings from tzres user32 = ctypes.WinDLL('user32') # Specify the LoadStringW function user32.LoadStringW.argtypes = (wintypes.HINSTANCE, wintypes.UINT, wintypes.LPWSTR, ctypes.c_int) self.LoadStringW = user32.LoadStringW self._tzres = ctypes.WinDLL(tzres_loc) # PyPy's WinDLL._handle is not a native HMODULE. Keep the DLL loaded # above and ask Windows for its handle instead. kernel32 = ctypes.WinDLL("kernel32") get_module_handle = kernel32.GetModuleHandleW get_module_handle.argtypes = (wintypes.LPCWSTR,) get_module_handle.restype = wintypes.HMODULE self._tzres_handle = get_module_handle(os.path.normpath(tzres_loc)) self.tzres_loc = tzres_loc def load_name(self, offset): """ Load a timezone name from a DLL offset (integer). >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.load_name(112)) 'Eastern Standard Time' :param offset: A positive integer value referring to a string from the tzres dll. .. note:: Offsets found in the registry are generally of the form ``@tzres.dll,-114``. The offset in this case is 114, not -114. """ resource = self.p_wchar() lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) nchar = self.LoadStringW(self._tzres_handle, offset, lpBuffer, 0) return resource[:nchar] def name_from_string(self, tzname_str): """ Parse strings as returned from the Windows registry into the time zone name as defined in the registry. >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.name_from_string('@tzres.dll,-251')) 'Dateline Daylight Time' >>> print(tzr.name_from_string('Eastern Standard Time')) 'Eastern Standard Time' :param tzname_str: A timezone name string as returned from a Windows registry key. :return: Returns the localized timezone string from tzres.dll if the string is of the form `@tzres.dll,-offset`, else returns the input string. """ if not tzname_str.startswith('@'): return tzname_str name_splt = tzname_str.split(',-') try: offset = int(name_splt[1]) except: raise ValueError("Malformed timezone string.") return self.load_name(offset) class tzwinbase(tzrangebase): """tzinfo class based on win32's timezones available in the registry.""" def __init__(self): raise NotImplementedError('tzwinbase is an abstract base class') def __eq__(self, other): # Compare on all relevant dimensions, including name. if not isinstance(other, tzwinbase): return NotImplemented return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._stddayofweek == other._stddayofweek and self._dstdayofweek == other._dstdayofweek and self._stdweeknumber == other._stdweeknumber and self._dstweeknumber == other._dstweeknumber and self._stdhour == other._stdhour and self._dsthour == other._dsthour and self._stdminute == other._stdminute and self._dstminute == other._dstminute and self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr) @staticmethod def list(): """Return a list of all time zones known to the system.""" with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: with winreg.OpenKey(handle, TZKEYNAME) as tzkey: result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] return result def display(self): """ Return the display name of the time zone. """ return self._display def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones. """ if not self.hasdst: return None dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, self._dsthour, self._dstminute, self._dstweeknumber) dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, self._stdhour, self._stdminute, self._stdweeknumber) # Ambiguous dates default to the STD side dstoff -= self._dst_base_offset return dston, dstoff def _get_hasdst(self): return self._dstmonth != 0 @property def _dst_base_offset(self): return self._dst_base_offset_ class tzwin(tzwinbase): """ Time zone object created from the zone info in the Windows registry These are similar to :py:class:`dateutil.tz.tzrange` objects in that the time zone data is provided in the format of a single offset rule for either 0 or 2 time zone transitions per year. :param: name The name of a Windows time zone key, e.g. "Eastern Standard Time". The full list of keys can be retrieved with :func:`tzwin.list`. """ def __init__(self, name): self._name = name with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: tzkeyname = "{kn}\\{name}".format(kn=TZKEYNAME, name=name) with winreg.OpenKey(handle, tzkeyname) as tzkey: keydict = valuestodict(tzkey) self._std_abbr = keydict["Std"] self._dst_abbr = keydict["Dlt"] self._display = keydict["Display"] # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm tup = struct.unpack("=3l16h", keydict["TZI"]) stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 dstoffset = stdoffset-tup[2] # + DaylightBias * -1 self._std_offset = datetime.timedelta(minutes=stdoffset) self._dst_offset = datetime.timedelta(minutes=dstoffset) # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs # http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx (self._stdmonth, self._stddayofweek, # Sunday = 0 self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[4:9] (self._dstmonth, self._dstdayofweek, # Sunday = 0 self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[12:17] self._dst_base_offset_ = self._dst_offset - self._std_offset self.hasdst = self._get_hasdst() def __repr__(self): return "tzwin(%s)" % repr(self._name) def __reduce__(self): return (self.__class__, (self._name,)) class tzwinlocal(tzwinbase): """ Class representing the local time zone information in the Windows registry While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time` module) to retrieve time zone information, ``tzwinlocal`` retrieves the rules directly from the Windows registry and creates an object like :class:`dateutil.tz.tzwin`. Because Windows does not have an equivalent of :func:`time.tzset`, on Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the time zone settings *at the time that the process was started*, meaning changes to the machine's time zone settings during the run of a program on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`. Because ``tzwinlocal`` reads the registry directly, it is unaffected by this issue. """ def __init__(self): with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey: keydict = valuestodict(tzlocalkey) self._std_abbr = keydict["StandardName"] self._dst_abbr = keydict["DaylightName"] try: tzkeyname = "{kn}\\{sn}".format(kn=TZKEYNAME, sn=self._std_abbr) with winreg.OpenKey(handle, tzkeyname) as tzkey: _keydict = valuestodict(tzkey) self._display = _keydict["Display"] except OSError: self._display = None stdoffset = -keydict["Bias"]-keydict["StandardBias"] dstoffset = stdoffset-keydict["DaylightBias"] self._std_offset = datetime.timedelta(minutes=stdoffset) self._dst_offset = datetime.timedelta(minutes=dstoffset) # For reasons unclear, in this particular key, the day of week has been # moved to the END of the SYSTEMTIME structure. tup = struct.unpack("=8h", keydict["StandardStart"]) (self._stdmonth, self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[1:5] self._stddayofweek = tup[7] tup = struct.unpack("=8h", keydict["DaylightStart"]) (self._dstmonth, self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[1:5] self._dstdayofweek = tup[7] self._dst_base_offset_ = self._dst_offset - self._std_offset self.hasdst = self._get_hasdst() def __repr__(self): return "tzwinlocal()" def __str__(self): # str will return the standard name, not the daylight name. return "tzwinlocal(%s)" % repr(self._std_abbr) def __reduce__(self): return (self.__class__, ()) def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ first = datetime.datetime(year, month, 1, hour, minute) # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), # Because 7 % 7 = 0 weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) wd = weekdayone + ((whichweek - 1) * ONEWEEK) if (wd.month != month): wd -= ONEWEEK return wd def valuestodict(key): """Convert a registry key's values to a dictionary.""" dout = {} size = winreg.QueryInfoKey(key)[1] tz_res = None for i in range(size): key_name, value, dtype = winreg.EnumValue(key, i) if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: # If it's a DWORD (32-bit integer), it's stored as unsigned - convert # that to a proper signed integer if value & (1 << 31): value = value - (1 << 32) elif dtype == winreg.REG_SZ: # If it's a reference to the tzres DLL, load the actual string if value.startswith('@tzres'): tz_res = tz_res or tzres() value = tz_res.name_from_string(value) value = value.rstrip('\x00') # Remove trailing nulls dout[key_name] = value return dout python_dateutil-4.0.0/src/dateutil/zoneinfo/__init__.py0000644000000000000000000001703113615410400020213 0ustar00""" The ``dateutil.zoneinfo`` module was originally designed to work with a tarball shipped with ``dateutil``. Since ``dateutil`` now uses data from the same sources as :py:mod:`zoneinfo`, this module is no longer necessary. .. caution:: This module is deprecated, and its functionality has been dramatically curtailed. It is recommended that you adopt the standard library module :py:mod:`zoneinfo` or :func:`dateutil.tz.gettz` instead. """ import json import sys import warnings from tarfile import TarFile from dateutil import _tzdata_impl from dateutil.tz import tzfile as _tzfile __all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] ZONEFILENAME = None METADATA_FN = 'METADATA' def _importer_stacklevel(): """The ``stacklevel`` that attributes a warning to the importing code. This module can be imported through ``dateutil.__getattr__`` (e.g. by ``from dateutil import zoneinfo``), which calls ``importlib.import_module``; the warnings machinery skips the import system's own frames, but not those two, so skip them here. """ level = 1 frame = sys._getframe(1) # The body of this module while frame.f_back is not None: frame = frame.f_back filename = frame.f_code.co_filename if "importlib" in filename and "_bootstrap" in filename: # The warnings machinery skips these frames without counting them. continue level += 1 if frame.f_globals.get("__name__") not in ("importlib", "dateutil"): return level return 2 warnings.warn( "The `dateutil.zoneinfo` module has been replaced with a wrapper around " "the tzdata package, and its use is deprecated, to be removed in a future " "version. Use the standard library module `zoneinfo` or `dateutil.tz` " "instead.", DeprecationWarning, stacklevel=_importer_stacklevel(), ) tzfile = _tzfile class ZoneInfoFile: def __init__(self, zonefile_stream=None): if zonefile_stream is not None: self._load_legacy_zonefile_stream(zonefile_stream) else: self._eager_load_tzdata() def _eager_load_tzdata(self): try: import tzdata except ImportError as e: raise ImportError( "The tzdata module is required to use ZoneInfoFile; either add a dependency on tzdata or migrate away from dateutil.zoneinfo." ) from e zone_dict = {} for key in _tzdata_impl._load_tzdata_keys(): with _tzdata_impl._load_tzdata(key) as f: zone_dict[key] = tzfile(f, key=key) self.zones = zone_dict self.metadata = { "metadata_version": "3.0", "tzversion": tzdata.IANA_VERSION, } def _load_legacy_zonefile_stream(self, zonefile_stream): with TarFile.open(fileobj=zonefile_stream) as tf: self.zones = { zf.name: tzfile(tf.extractfile(zf), filename=zf.name) for zf in tf.getmembers() if zf.isfile() and zf.name != METADATA_FN } # deal with links: They'll point to their parent object. Less # waste of memory links = { zl.name: self.zones[zl.linkname] for zl in tf.getmembers() if zl.islnk() or zl.issym() } self.zones.update(links) try: metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) metadata_str = metadata_json.read().decode("UTF-8") self.metadata = json.loads(metadata_str) except KeyError: # no metadata in tar file self.metadata = None def get(self, name, default=None): """ Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method for retrieving zones from the zone dictionary. :param name: The name of the zone to retrieve. (Generally IANA zone names) :param default: The value to return in the event of a missing key. .. versionadded:: 2.6.0 """ return self.zones.get(name, default) # The current API has gettz as a module function, although in fact it taps into # a stateful class. So as a workaround for now, without changing the API, we # will create a new "global" class instance the first time a user requests a # timezone. Ugly, but adheres to the api. # # TODO: Remove after deprecation period. _CLASS_ZONE_INSTANCE = [] def get_zonefile_instance(new_instance=False): """ This is a convenience function which provides a :class:`ZoneInfoFile` instance using the data provided by the ``dateutil`` package. By default, it caches a single instance of the ZoneInfoFile object and returns that. :param new_instance: If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and used as the cached instance for the next call. Otherwise, new instances are created only as necessary. :return: Returns a :class:`ZoneInfoFile` object. .. versionadded:: 2.6 """ if new_instance: zif = None else: zif = getattr(get_zonefile_instance, '_cached_instance', None) if zif is None: zif = ZoneInfoFile() get_zonefile_instance._cached_instance = zif return zif def gettz(name): """ This retrieves a time zone from the ``tzdata`` package. :param name: An IANA-style time zone name, as found in the zoneinfo file. :return: Returns a :class:`dateutil.tz.tzfile` time zone object. .. warning:: It is generally inadvisable to use this function, and it is only provided for API compatibility with earlier versions. This is *not* equivalent to ``dateutil.tz.gettz()``, which selects an appropriate time zone based on the inputs, favoring system zoneinfo. This is ONLY for accessing the dateutil-specific zoneinfo (which may be out of date compared to the system zoneinfo). .. deprecated:: 2.6 If you need to use a specific zoneinfofile over the system zoneinfo, instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead. Use :func:`get_zonefile_instance` to retrieve an instance of the dateutil-provided zoneinfo. """ warnings.warn("zoneinfo.gettz() will be removed in future versions, " "to use the dateutil-provided zoneinfo files, instantiate a " "ZoneInfoFile object and use ZoneInfoFile.zones.get() " "instead. See the documentation for details.", DeprecationWarning) if len(_CLASS_ZONE_INSTANCE) == 0: _CLASS_ZONE_INSTANCE.append(ZoneInfoFile()) return _CLASS_ZONE_INSTANCE[0].zones.get(name) def gettz_db_metadata(): """Get the zonefile metadata :returns: A dictionary with the database metadata .. deprecated:: 2.6 See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, query the attribute ``zoneinfo.ZoneInfoFile.metadata``. """ warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future " "versions, to use the dateutil-provided zoneinfo files, " "ZoneInfoFile object and query the 'metadata' attribute " "instead. See the documentation for details.", DeprecationWarning) if len(_CLASS_ZONE_INSTANCE) == 0: _CLASS_ZONE_INSTANCE.append(ZoneInfoFile()) return _CLASS_ZONE_INSTANCE[0].metadata python_dateutil-4.0.0/src/dateutil/zoneinfo/rebuild.py0000644000000000000000000000313113615410400020076 0ustar00import warnings __all__ = ["rebuild", "RebuildDeprecationWarning"] class RebuildDeprecationWarning(FutureWarning): """Warning raised by :func:`rebuild`, which no longer does anything. A warnings filter turns this into an error by default. To keep calling :func:`rebuild` as a no-op, filter it out, e.g.:: warnings.filterwarnings( "ignore", category=dateutil.zoneinfo.rebuild.RebuildDeprecationWarning ) """ def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): """Formerly rebuilt the zoneinfo tarball bundled with ``dateutil``. ``dateutil`` no longer ships a zoneinfo tarball; it reads time zone data from the system and from the `tzdata `_ package instead. This function now does nothing except raise :class:`RebuildDeprecationWarning`, which is an error unless a warnings filter says otherwise. .. deprecated:: 3.0.0 """ # The filter is added at call time rather than at import time, so that it # is still in place if the module was first imported inside a # warnings.catch_warnings() block. It is appended, so any filter the user # has installed for this category takes precedence. warnings.filterwarnings( "error", category=RebuildDeprecationWarning, append=True ) warnings.warn( "dateutil.zoneinfo.rebuild() no longer does anything, because dateutil " "no longer ships a zoneinfo tarball. Use the tzdata package or the " "system time zone data instead.", RebuildDeprecationWarning, stacklevel=2, ) python_dateutil-4.0.0/tests/__init__.py0000644000000000000000000000000013615410400015110 0ustar00python_dateutil-4.0.0/tests/_common.py0000644000000000000000000002427113615410400015020 0ustar00import contextlib import os import pickle import subprocess import sys import tempfile import threading import time import pytest from dateutil import tz #### # Selecting the source of time zone data # # TZPATH, the gettz cache and whether the tzdata package can be imported are # all process-wide, so tests that change them take this lock. It is reentrant # so that a test running under a fixture that holds it can still use # set_tzpath itself. TZPATH_LOCK = threading.RLock() contextdecorator = contextlib.contextmanager def pop_tzdata_modules(): tzdata_modules = {} for modname in list(sys.modules): if modname.split(".", 1)[0] != "tzdata": # pragma: nocover continue tzdata_modules[modname] = sys.modules.pop(modname) return tzdata_modules @contextdecorator def set_tzpath(tzpath, block_tzdata=False, clear_cache=True): tzdata_modules = {} with TZPATH_LOCK: if block_tzdata: tzdata_modules = pop_tzdata_modules() sys.modules["tzdata"] = None old_tzpath = tuple(tz.TZPATH) try: tz._tzpath.reset_tzpath(to=tzpath) # Zones already in the cache may have come from somewhere else # (another TZPATH, or tzdata when it is now blocked), and zones # cached in here must not leak out, so clear it on both ends. if clear_cache: tz.gettz.cache_clear() yield finally: if block_tzdata: sys.modules.pop("tzdata", None) sys.modules.update(tzdata_modules) tz._tzpath.reset_tzpath(to=old_tzpath) if clear_cache: tz.gettz.cache_clear() TZ_SOURCES = ("tzpath", "tzdata") def tz_source_skip_reason(source): """Why tests can't run against ``source`` here, or None if they can. ``"tzpath"`` is the time zone data on TZPATH (the system data, or whatever PYTHONTZPATH points at) with the tzdata package blocked, so that a key that is missing or broken there fails rather than being answered by tzdata. ``"tzdata"`` is the tzdata package, with an empty TZPATH. """ if source == "tzpath": # Any real installation of the data has one of these (depending on # whether the "backward" links were installed); anything else, like # an empty directory, is treated as no data at all. if not any( os.path.isfile(os.path.join(path, *key.split("/"))) for path in tz.TZPATH for key in ("Etc/UTC", "UTC") ): return "No time zone data on TZPATH" elif source == "tzdata": try: import tzdata # noqa: F401 except ImportError: return "tzdata is not installed" else: # pragma: nocover raise ValueError("Unknown time zone data source: %r" % (source,)) return None def tz_source_context(source): """A context manager that makes ``source`` the only time zone data.""" if source == "tzpath": return set_tzpath(tuple(tz.TZPATH), block_tzdata=True) else: return set_tzpath((), block_tzdata=False) class TzSourceMixin: """Runs the tests in a TestCase against a single source of time zone data. unittest.TestCase subclasses can't use parametrized pytest fixtures, so to run a set of tests against more than one source, subclass the test case and override ``tz_source``. A ``tz_source`` of None leaves everything as it is. """ tz_source = "tzpath" def setUp(self): super().setUp() if self.tz_source is None: return reason = tz_source_skip_reason(self.tz_source) if reason is not None: self.skipTest(reason) context = tz_source_context(self.tz_source) context.__enter__() self.addCleanup(context.__exit__, None, None, None) class PicklableMixin: def _get_nobj_bytes(self, obj, dump_kwargs, load_kwargs): """ Pickle and unpickle an object using ``pickle.dumps`` / ``pickle.loads`` """ pkl = pickle.dumps(obj, **dump_kwargs) return pickle.loads(pkl, **load_kwargs) def _get_nobj_file(self, obj, dump_kwargs, load_kwargs): """ Pickle and unpickle an object using ``pickle.dump`` / ``pickle.load`` on a temporary file. """ with tempfile.TemporaryFile('w+b') as pkl: pickle.dump(obj, pkl, **dump_kwargs) pkl.seek(0) # Reset the file to the beginning to read it nobj = pickle.load(pkl, **load_kwargs) return nobj def assertPicklable(self, obj, singleton=False, asfile=False, dump_kwargs=None, load_kwargs=None): """ Assert that an object can be pickled and unpickled. This assertion assumes that the desired behavior is that the unpickled object is the same as the original, when singleton=True. """ get_nobj = self._get_nobj_file if asfile else self._get_nobj_bytes dump_kwargs = dump_kwargs or {} load_kwargs = load_kwargs or {} nobj = get_nobj(obj, dump_kwargs, load_kwargs) if singleton: self.assertIs(obj, nobj) else: self.assertIsNot(obj, nobj) self.assertEqual(obj, nobj) class TZContextBase: """ Base class for a context manager which allows changing of time zones. Subclasses may define a guard variable to either block or or allow time zone changes by redefining ``_guard_var_name`` and ``_guard_allows_change``. The default is that the guard variable must be affirmatively set. Subclasses must define ``get_current_tz`` and ``set_current_tz``. """ _guard_var_name = "DATEUTIL_MAY_CHANGE_TZ" _guard_allows_change = True def __init__(self, tzval): self.tzval = tzval self._old_tz = None @classmethod def tz_change_allowed(cls): """ Class method used to query whether or not this class allows time zone changes. """ guard = bool(os.environ.get(cls._guard_var_name, False)) # _guard_allows_change gives the "default" behavior - if True, the # guard is overcoming a block. If false, the guard is causing a block. # Whether tz_change is allowed is therefore the XNOR of the two. return guard == cls._guard_allows_change @classmethod def tz_change_disallowed_message(cls): """ Generate instructions on how to allow tz changes """ msg = ('Changing time zone not allowed. Set {envar} to {gval} ' 'if you would like to allow this behavior') return msg.format(envar=cls._guard_var_name, gval=cls._guard_allows_change) def __enter__(self): if not self.tz_change_allowed(): msg = self.tz_change_disallowed_message() pytest.skip(msg) # If this is used outside of a test suite, we still want an error. raise ValueError(msg) # pragma: no cover self._old_tz = self.get_current_tz() self.set_current_tz(self.tzval) def __exit__(self, type, value, traceback): if self._old_tz is not None: self.set_current_tz(self._old_tz) self._old_tz = None def get_current_tz(self): raise NotImplementedError def set_current_tz(self): raise NotImplementedError class TZEnvContext(TZContextBase): """ Context manager that temporarily sets the `TZ` variable (for use on *nix-like systems). Because the effect is local to the shell anyway, this will apply *unless* a guard is set. If you do not want the TZ environment variable set, you may set the ``DATEUTIL_MAY_NOT_CHANGE_TZ_VAR`` variable to a truthy value. """ _guard_var_name = "DATEUTIL_MAY_NOT_CHANGE_TZ_VAR" _guard_allows_change = False def get_current_tz(self): return os.environ.get('TZ', UnsetTz) def set_current_tz(self, tzval): if tzval is UnsetTz and 'TZ' in os.environ: del os.environ['TZ'] else: os.environ['TZ'] = tzval time.tzset() class TZWinContext(TZContextBase): """ Context manager for changing local time zone on Windows. Because the effect of this is system-wide and global, it may have unintended side effect. Set the ``DATEUTIL_MAY_CHANGE_TZ`` environment variable to a truthy value before using this context manager. """ def get_current_tz(self): p = subprocess.Popen(['tzutil', '/g'], stdout=subprocess.PIPE) ctzname, err = p.communicate() ctzname = ctzname.decode() # Popen returns if p.returncode: raise OSError('Failed to get current time zone: ' + err) return ctzname def set_current_tz(self, tzname): p = subprocess.Popen('tzutil /s "' + tzname + '"') out, err = p.communicate() if p.returncode: raise OSError('Failed to set current time zone: ' + (err or 'Unknown error.')) ### # Utility classes class NotAValueClass: """ A class analogous to NaN that has operations defined for any type. """ def _op(self, other): return self # Operation with NotAValue returns NotAValue def _cmp(self, other): return False __add__ = __radd__ = _op __sub__ = __rsub__ = _op __mul__ = __rmul__ = _op __truediv__ = __rtruediv__ = _op __floordiv__ = __rfloordiv__ = _op __lt__ = __rlt__ = _op __gt__ = __rgt__ = _op __eq__ = __req__ = _op __le__ = __rle__ = _op __ge__ = __rge__ = _op NotAValue = NotAValueClass() class ComparesEqualClass: """ A class that is always equal to whatever you compare it to. """ def __eq__(self, other): return True def __ne__(self, other): return False def __le__(self, other): return True def __ge__(self, other): return True def __lt__(self, other): return False def __gt__(self, other): return False __req__ = __eq__ __rne__ = __ne__ __rle__ = __le__ __rge__ = __ge__ __rlt__ = __lt__ __rgt__ = __gt__ ComparesEqual = ComparesEqualClass() class UnsetTzClass: """ Sentinel class for unset time zone variable """ pass UnsetTz = UnsetTzClass() python_dateutil-4.0.0/tests/conftest.py0000644000000000000000000000251613615410400015214 0ustar00import pytest from ._common import ( TZ_SOURCES, set_tzpath, tz_source_context, tz_source_skip_reason, ) # Configure pytest to ignore xfailing tests # See: https://stackoverflow.com/a/53198349/467366 def pytest_collection_modifyitems(items): for item in items: marker = item.get_closest_marker("xfail") # Need to query the args because conditional xfail tests still have # the xfail mark even if they are not expected to fail if marker and (not marker.args or marker.args[0]): item.add_marker(pytest.mark.no_cover) @pytest.fixture(params=TZ_SOURCES) def tz_source(request): """Runs a test against each source of IANA time zone data in turn. With ``"tzpath"``, only the data on TZPATH is used and the tzdata package is blocked, so a key that is missing or broken there makes the test fail instead of being silently answered by tzdata. With ``"tzdata"``, only the tzdata package is used. """ reason = tz_source_skip_reason(request.param) if reason is not None: pytest.skip(reason) with tz_source_context(request.param): yield request.param @pytest.fixture def block_tzdata(): """Makes the tzdata package impossible to import.""" from dateutil import tz with set_tzpath(tuple(tz.TZPATH), block_tzdata=True): yield python_dateutil-4.0.0/tests/test_easter.py0000644000000000000000000001023213615410400015703 0ustar00from dateutil.easter import easter from dateutil.easter import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import pytest # List of easters between 1990 and 2050 western_easter_dates = [ date(1990, 4, 15), date(1991, 3, 31), date(1992, 4, 19), date(1993, 4, 11), date(1994, 4, 3), date(1995, 4, 16), date(1996, 4, 7), date(1997, 3, 30), date(1998, 4, 12), date(1999, 4, 4), date(2000, 4, 23), date(2001, 4, 15), date(2002, 3, 31), date(2003, 4, 20), date(2004, 4, 11), date(2005, 3, 27), date(2006, 4, 16), date(2007, 4, 8), date(2008, 3, 23), date(2009, 4, 12), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 8), date(2013, 3, 31), date(2014, 4, 20), date(2015, 4, 5), date(2016, 3, 27), date(2017, 4, 16), date(2018, 4, 1), date(2019, 4, 21), date(2020, 4, 12), date(2021, 4, 4), date(2022, 4, 17), date(2023, 4, 9), date(2024, 3, 31), date(2025, 4, 20), date(2026, 4, 5), date(2027, 3, 28), date(2028, 4, 16), date(2029, 4, 1), date(2030, 4, 21), date(2031, 4, 13), date(2032, 3, 28), date(2033, 4, 17), date(2034, 4, 9), date(2035, 3, 25), date(2036, 4, 13), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 10), date(2040, 4, 1), date(2041, 4, 21), date(2042, 4, 6), date(2043, 3, 29), date(2044, 4, 17), date(2045, 4, 9), date(2046, 3, 25), date(2047, 4, 14), date(2048, 4, 5), date(2049, 4, 18), date(2050, 4, 10) ] orthodox_easter_dates = [ date(1990, 4, 15), date(1991, 4, 7), date(1992, 4, 26), date(1993, 4, 18), date(1994, 5, 1), date(1995, 4, 23), date(1996, 4, 14), date(1997, 4, 27), date(1998, 4, 19), date(1999, 4, 11), date(2000, 4, 30), date(2001, 4, 15), date(2002, 5, 5), date(2003, 4, 27), date(2004, 4, 11), date(2005, 5, 1), date(2006, 4, 23), date(2007, 4, 8), date(2008, 4, 27), date(2009, 4, 19), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 15), date(2013, 5, 5), date(2014, 4, 20), date(2015, 4, 12), date(2016, 5, 1), date(2017, 4, 16), date(2018, 4, 8), date(2019, 4, 28), date(2020, 4, 19), date(2021, 5, 2), date(2022, 4, 24), date(2023, 4, 16), date(2024, 5, 5), date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2), date(2028, 4, 16), date(2029, 4, 8), date(2030, 4, 28), date(2031, 4, 13), date(2032, 5, 2), date(2033, 4, 24), date(2034, 4, 9), date(2035, 4, 29), date(2036, 4, 20), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 17), date(2040, 5, 6), date(2041, 4, 21), date(2042, 4, 13), date(2043, 5, 3), date(2044, 4, 24), date(2045, 4, 9), date(2046, 4, 29), date(2047, 4, 21), date(2048, 4, 5), date(2049, 4, 25), date(2050, 4, 17) ] # A random smattering of Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date( 326, 4, 3), date( 375, 4, 5), date( 492, 4, 5), date( 552, 3, 31), date( 562, 4, 9), date( 569, 4, 21), date( 597, 4, 14), date( 621, 4, 19), date( 636, 3, 31), date( 655, 3, 29), date( 700, 4, 11), date( 725, 4, 8), date( 750, 3, 29), date( 782, 4, 7), date( 835, 4, 18), date( 849, 4, 14), date( 867, 3, 30), date( 890, 4, 12), date( 922, 4, 21), date( 934, 4, 6), date(1049, 3, 26), date(1058, 4, 19), date(1113, 4, 6), date(1119, 3, 30), date(1242, 4, 20), date(1255, 3, 28), date(1257, 4, 8), date(1258, 3, 24), date(1261, 4, 24), date(1278, 4, 17), date(1333, 4, 4), date(1351, 4, 17), date(1371, 4, 6), date(1391, 3, 26), date(1402, 3, 26), date(1412, 4, 3), date(1439, 4, 5), date(1445, 3, 28), date(1531, 4, 9), date(1555, 4, 14) ] @pytest.mark.parametrize("easter_date", western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize("easter_date", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize("easter_date", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN) def test_easter_bad_method(): with pytest.raises(ValueError): easter(1975, 4) python_dateutil-4.0.0/tests/test_import_star.py0000644000000000000000000000173313615410400016771 0ustar00"""Test for the "import *" functionality. As import * can be only done at module level, it has been added in a separate file """ import pytest prev_locals = list(locals()) from dateutil import * new_locals = {name:value for name,value in locals().items() if name not in prev_locals} new_locals.pop('prev_locals') @pytest.mark.import_star def test_imported_modules(): """ Test that `from dateutil import *` adds modules in __all__ locally """ import dateutil.easter import dateutil.parser import dateutil.relativedelta import dateutil.rrule import dateutil.tz import dateutil.utils assert dateutil.easter == new_locals.pop("easter") assert dateutil.parser == new_locals.pop("parser") assert dateutil.relativedelta == new_locals.pop("relativedelta") assert dateutil.rrule == new_locals.pop("rrule") assert dateutil.tz == new_locals.pop("tz") assert dateutil.utils == new_locals.pop("utils") assert not new_locals python_dateutil-4.0.0/tests/test_imports.py0000644000000000000000000001561213615410400016124 0ustar00import importlib.metadata import os import subprocess import sys import pytest MODULE_TYPE = type(sys) @pytest.fixture(scope="function") def clean_import(): """Create a somewhat clean import base for lazy import tests""" du_modules = { mod_name: mod for mod_name, mod in sys.modules.items() if mod_name.startswith("dateutil") } other_modules = { mod_name for mod_name in sys.modules if mod_name not in du_modules } for mod_name in du_modules: del sys.modules[mod_name] yield # Delete anything that wasn't in the origin sys.modules list for mod_name in list(sys.modules): if mod_name not in other_modules: del sys.modules[mod_name] # Restore original modules for mod_name, mod in du_modules.items(): sys.modules[mod_name] = mod @pytest.mark.parametrize( "module", ["easter", "parser", "relativedelta", "rrule", "tz", "utils"], ) def test_lazy_import(clean_import, module): """Test that dateutil.[submodule] loads lazily""" import importlib import dateutil mod_obj = getattr(dateutil, module, None) assert isinstance(mod_obj, MODULE_TYPE) mod_imported = importlib.import_module("dateutil.%s" % module) assert mod_obj is mod_imported def assert_warned_from_this_file(record): """The zoneinfo deprecation warning is attributed to the importing code.""" filenames = [ os.path.normcase(os.path.splitext(w.filename)[0]) for w in record if issubclass(w.category, DeprecationWarning) ] assert filenames == [os.path.normcase(os.path.splitext(__file__)[0])] def test_lazy_import_zoneinfo(clean_import): """Test that zoneinfo raises a DeprecationWarning when imported lazily.""" import dateutil with pytest.warns(DeprecationWarning) as record: assert dateutil.zoneinfo is not None assert_warned_from_this_file(record) HOST_IS_WINDOWS = sys.platform.startswith('win') def test_import_version_str(): """ Test that dateutil.__version__ can be imported""" from dateutil import __version__ def test_import_version_root(): import dateutil assert hasattr(dateutil, '__version__') def test_version_matches_distribution_metadata() -> None: import dateutil assert dateutil.__version__ == importlib.metadata.version("python-dateutil") # Test that dateutil.easter-related imports work properly def test_import_easter_direct(): import dateutil.easter def test_import_easter_from(): from dateutil import easter def test_import_easter_start(): from dateutil.easter import easter # Test that dateutil.parser-related imports work properly def test_import_parser_direct(): import dateutil.parser def test_import_parser_from(): from dateutil import parser def test_import_parser_all(): # All interface # Other public classes from dateutil.parser import parse, parser, parserinfo for var in (parse, parserinfo, parser): assert var is not None # Test that dateutil.relativedelta-related imports work properly def test_import_relative_delta_direct(): import dateutil.relativedelta def test_import_relative_delta_from(): from dateutil import relativedelta def test_import_relative_delta_all(): from dateutil.relativedelta import FR, MO, SA, SU, TH, TU, WE, relativedelta for var in (relativedelta, MO, TU, WE, TH, FR, SA, SU): assert var is not None # In the public interface but not in all from dateutil.relativedelta import weekday assert weekday is not None # Test that dateutil.rrule related imports work properly def test_import_rrule_direct(): import dateutil.rrule def test_import_rrule_from(): from dateutil import rrule def test_import_rrule_all(): from dateutil.rrule import ( DAILY, FR, HOURLY, MINUTELY, MO, MONTHLY, SA, SECONDLY, SU, TH, TU, WE, WEEKLY, YEARLY, rrule, rruleset, rrulestr, ) rr_all = (rrule, rruleset, rrulestr, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, MO, TU, WE, TH, FR, SA, SU) for var in rr_all: assert var is not None # In the public interface but not in all from dateutil.rrule import weekday assert weekday is not None # Test that dateutil.tz related imports work properly def test_import_tztest_direct(): import dateutil.tz def test_import_tz_from(): from dateutil import tz def test_import_tz_all(): from dateutil.tz import ( UTC, datetime_ambiguous, datetime_exists, gettz, resolve_imaginary, tzfile, tzical, tzlocal, tzoffset, tzrange, tzstr, tzutc, tzwin, tzwinlocal, ) tz_all = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", "tzstr", "tzical", "gettz", "datetime_ambiguous", "datetime_exists", "resolve_imaginary", "UTC"] tz_all += ["tzwin", "tzwinlocal"] if sys.platform.startswith("win") else [] lvars = locals() for var in tz_all: assert lvars[var] is not None # Test that dateutil.tzwin related imports work properly @pytest.mark.skipif(not HOST_IS_WINDOWS, reason="Requires Windows") def test_import_tz_windows_direct(): import dateutil.tzwin @pytest.mark.skipif(not HOST_IS_WINDOWS, reason="Requires Windows") def test_import_tz_windows_from(): from dateutil import tzwin @pytest.mark.skipif(not HOST_IS_WINDOWS, reason="Requires Windows") def test_import_tz_windows_star(): from dateutil.tzwin import tzwin, tzwinlocal tzwin_all = [tzwin, tzwinlocal] for var in tzwin_all: assert var is not None # Test imports of Zone Info def test_import_zone_info_direct(clean_import): with pytest.warns(DeprecationWarning) as record: import dateutil.zoneinfo assert_warned_from_this_file(record) def test_import_zone_info_from(clean_import): with pytest.warns(DeprecationWarning) as record: from dateutil import zoneinfo assert_warned_from_this_file(record) def test_import_zone_info_star(clean_import): with pytest.warns(DeprecationWarning) as record: from dateutil.zoneinfo import gettz, gettz_db_metadata, rebuild assert_warned_from_this_file(record) zi_all = (gettz, gettz_db_metadata, rebuild) for var in zi_all: assert var is not None def test_import_without_six() -> None: """Imports the public modules with six unavailable.""" code = """ import sys import warnings sys.modules["six"] = None from dateutil import easter, parser, relativedelta, rrule, tz, utils if sys.platform == "win32": from dateutil import tzwin with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) from dateutil import zoneinfo """ subprocess.run([sys.executable, "-c", code], check=True) python_dateutil-4.0.0/tests/test_internals.py0000644000000000000000000000414013615410400016420 0ustar00""" Tests for implementation details, not necessarily part of the user-facing API. The motivating case for these tests is #483, where we want to smoke-test code that may be difficult to reach through the standard API calls. """ import pytest import warnings from dateutil.parser._parser import _ymd from dateutil import tz @pytest.mark.smoke def test_YMD_could_be_day(): ymd = _ymd('foo bar 124 baz') ymd.append(2, 'M') assert ymd.has_month assert not ymd.has_year assert ymd.could_be_day(4) assert not ymd.could_be_day(-6) assert not ymd.could_be_day(32) # Assumes leap year assert ymd.could_be_day(29) ymd.append(1999) assert ymd.has_year assert not ymd.could_be_day(29) ymd.append(16, 'D') assert ymd.has_day assert not ymd.could_be_day(1) ymd = _ymd('foo bar 124 baz') ymd.append(1999) assert ymd.could_be_day(31) ### # Test that private interfaces in _parser are deprecated properly def test_parser_private_warns(): from dateutil.parser import _timelex, _tzparser from dateutil.parser import _parsetz with pytest.warns(DeprecationWarning): _tzparser() with pytest.warns(DeprecationWarning): _timelex('2014-03-03') with pytest.warns(DeprecationWarning): _parsetz('+05:00') def test_parser_parser_private_not_warns(): from dateutil.parser._parser import _timelex, _tzparser from dateutil.parser._parser import _parsetz with warnings.catch_warnings(): warnings.simplefilter("error") _tzparser() with warnings.catch_warnings(): warnings.simplefilter("error") _timelex('2014-03-03') with warnings.catch_warnings(): warnings.simplefilter("error") _parsetz('+05:00') @pytest.mark.tzstr def test_tzstr_internal_timedeltas(): with pytest.warns(tz.DeprecatedTzFormatWarning): tz1 = tz.tzstr("EST5EDT,5,4,0,7200,11,-3,0,7200") with pytest.warns(tz.DeprecatedTzFormatWarning): tz2 = tz.tzstr("EST5EDT,4,1,0,7200,10,-1,0,7200") assert tz1._start_delta != tz2._start_delta assert tz1._end_delta != tz2._end_delta python_dateutil-4.0.0/tests/test_isoparser.py0000644000000000000000000004343613615410400016443 0ustar00from datetime import datetime, timedelta, date, time import itertools as it from dateutil import tz from dateutil.tz import UTC from dateutil.parser import isoparser, isoparse import pytest def _generate_tzoffsets(limited): def _mkoffset(hmtuple, fmt): h, m = hmtuple m_td = (-1 if h < 0 else 1) * m tzo = tz.tzoffset(None, timedelta(hours=h, minutes=m_td)) return tzo, fmt.format(h, m) out = [] if not limited: # The subset that's just hours hm_out_h = [(h, 0) for h in (-23, -5, 0, 5, 23)] out.extend([_mkoffset(hm, '{:+03d}') for hm in hm_out_h]) # Ones that have hours and minutes hm_out = [] + hm_out_h hm_out += [(-12, 15), (11, 30), (10, 2), (5, 15), (-5, 30)] else: hm_out = [(-5, -0)] fmts = ['{:+03d}:{:02d}', '{:+03d}{:02d}'] out += [_mkoffset(hm, fmt) for hm in hm_out for fmt in fmts] # Also add in UTC and naive out.append((UTC, 'Z')) out.append((None, '')) return out FULL_TZOFFSETS = _generate_tzoffsets(False) FULL_TZOFFSETS_AWARE = [x for x in FULL_TZOFFSETS if x[1]] TZOFFSETS = _generate_tzoffsets(True) DATES = [datetime(1996, 1, 1), datetime(2017, 1, 1)] @pytest.mark.parametrize('dt', tuple(DATES)) def test_year_only(dt): dtstr = dt.strftime('%Y') assert isoparse(dtstr) == dt DATES += [datetime(2000, 2, 1), datetime(2017, 4, 1)] @pytest.mark.parametrize('dt', tuple(DATES)) def test_year_month(dt): fmt = '%Y-%m' dtstr = dt.strftime(fmt) assert isoparse(dtstr) == dt DATES += [datetime(2016, 2, 29), datetime(2018, 3, 15)] YMD_FMTS = ('%Y%m%d', '%Y-%m-%d') @pytest.mark.parametrize('dt', tuple(DATES)) @pytest.mark.parametrize('fmt', YMD_FMTS) def test_year_month_day(dt, fmt): dtstr = dt.strftime(fmt) assert isoparse(dtstr) == dt def _isoparse_date_and_time(dt, date_fmt, time_fmt, tzoffset, microsecond_precision=None): tzi, offset_str = tzoffset fmt = date_fmt + 'T' + time_fmt dt = dt.replace(tzinfo=tzi) dtstr = dt.strftime(fmt) if microsecond_precision is not None: if not fmt.endswith('%f'): # pragma: nocover raise ValueError('Time format has no microseconds!') if microsecond_precision != 6: dtstr = dtstr[: -(6 - microsecond_precision)] elif microsecond_precision > 6: # pragma: nocover raise ValueError("Precision must be 1-6") dtstr += offset_str assert isoparse(dtstr) == dt DATETIMES = [datetime(1998, 4, 16, 12), datetime(2019, 11, 18, 23), datetime(2014, 12, 16, 4)] @pytest.mark.parametrize('dt', tuple(DATETIMES)) @pytest.mark.parametrize('date_fmt', YMD_FMTS) @pytest.mark.parametrize('tzoffset', TZOFFSETS) def test_ymd_h(dt, date_fmt, tzoffset): _isoparse_date_and_time(dt, date_fmt, '%H', tzoffset) DATETIMES = [datetime(2012, 1, 6, 9, 37)] @pytest.mark.parametrize('dt', tuple(DATETIMES)) @pytest.mark.parametrize('date_fmt', YMD_FMTS) @pytest.mark.parametrize('time_fmt', ('%H%M', '%H:%M')) @pytest.mark.parametrize('tzoffset', TZOFFSETS) def test_ymd_hm(dt, date_fmt, time_fmt, tzoffset): _isoparse_date_and_time(dt, date_fmt, time_fmt, tzoffset) DATETIMES = [datetime(2003, 9, 2, 22, 14, 2), datetime(2003, 8, 8, 14, 9, 14), datetime(2003, 4, 7, 6, 14, 59)] HMS_FMTS = ('%H%M%S', '%H:%M:%S') @pytest.mark.parametrize('dt', tuple(DATETIMES)) @pytest.mark.parametrize('date_fmt', YMD_FMTS) @pytest.mark.parametrize('time_fmt', HMS_FMTS) @pytest.mark.parametrize('tzoffset', TZOFFSETS) def test_ymd_hms(dt, date_fmt, time_fmt, tzoffset): _isoparse_date_and_time(dt, date_fmt, time_fmt, tzoffset) DATETIMES = [datetime(2017, 11, 27, 6, 14, 30, 123456)] @pytest.mark.parametrize("dt", tuple(DATETIMES)) @pytest.mark.parametrize("date_fmt", YMD_FMTS) @pytest.mark.parametrize( "time_fmt", [x + sep + "%f" for x in HMS_FMTS for sep in ".,"] ) @pytest.mark.parametrize("tzoffset", TZOFFSETS) @pytest.mark.parametrize("precision", list(range(3, 7))) def test_ymd_hms_micro(dt, date_fmt, time_fmt, tzoffset, precision): # Truncate the microseconds to the desired precision for the representation dt = dt.replace(microsecond=int(round(dt.microsecond, precision-6))) _isoparse_date_and_time(dt, date_fmt, time_fmt, tzoffset, precision) ### # Truncation of extra digits beyond microsecond precision @pytest.mark.parametrize('dt_str', [ '2018-07-03T14:07:00.123456000001', '2018-07-03T14:07:00.123456999999', ]) def test_extra_subsecond_digits(dt_str): assert isoparse(dt_str) == datetime(2018, 7, 3, 14, 7, 0, 123456) @pytest.mark.parametrize('tzoffset', FULL_TZOFFSETS) def test_full_tzoffsets(tzoffset): dt = datetime(2017, 11, 27, 6, 14, 30, 123456) date_fmt = '%Y-%m-%d' time_fmt = '%H:%M:%S.%f' _isoparse_date_and_time(dt, date_fmt, time_fmt, tzoffset) @pytest.mark.parametrize('dt_str', [ '2014-04-11T00', '2014-04-10T24', '2014-04-11T00:00', '2014-04-10T24:00', '2014-04-11T00:00:00', '2014-04-10T24:00:00', '2014-04-11T00:00:00.000', '2014-04-10T24:00:00.000', '2014-04-11T00:00:00.000000', '2014-04-10T24:00:00.000000'] ) def test_datetime_midnight(dt_str): assert isoparse(dt_str) == datetime(2014, 4, 11, 0, 0, 0, 0) @pytest.mark.parametrize('datestr', [ '2014-01-01', '20140101', ]) @pytest.mark.parametrize('sep', [' ', 'a', 'T', '_', '-']) def test_isoparse_sep_none(datestr, sep): isostr = datestr + sep + '14:33:09' assert isoparse(isostr) == datetime(2014, 1, 1, 14, 33, 9) ## # Uncommon date formats TIME_ARGS = ('time_args', ((None, time(0), None), ) + tuple(('%H:%M:%S.%f', _t, _tz) for _t, _tz in it.product([time(0), time(9, 30), time(14, 47)], TZOFFSETS))) @pytest.mark.parametrize('isocal,dt_expected',[ ((2017, 10), datetime(2017, 3, 6)), ((2020, 1), datetime(2019, 12, 30)), # ISO year != Cal year ((2004, 53), datetime(2004, 12, 27)), # Only half the week is in 2014 ]) def test_isoweek(isocal, dt_expected): # TODO: Figure out how to parametrize this on formats, too for fmt in ('{:04d}-W{:02d}', '{:04d}W{:02d}'): dtstr = fmt.format(*isocal) assert isoparse(dtstr) == dt_expected @pytest.mark.parametrize('isocal,dt_expected',[ ((2016, 13, 7), datetime(2016, 4, 3)), ((2004, 53, 7), datetime(2005, 1, 2)), # ISO year != Cal year ((2009, 1, 2), datetime(2008, 12, 30)), # ISO year < Cal year ((2009, 53, 6), datetime(2010, 1, 2)) # ISO year > Cal year ]) def test_isoweek_day(isocal, dt_expected): # TODO: Figure out how to parametrize this on formats, too for fmt in ('{:04d}-W{:02d}-{:d}', '{:04d}W{:02d}{:d}'): dtstr = fmt.format(*isocal) assert isoparse(dtstr) == dt_expected @pytest.mark.parametrize('isoord,dt_expected', [ ((2004, 1), datetime(2004, 1, 1)), ((2016, 60), datetime(2016, 2, 29)), ((2017, 60), datetime(2017, 3, 1)), ((2016, 366), datetime(2016, 12, 31)), ((2017, 365), datetime(2017, 12, 31)) ]) def test_iso_ordinal(isoord, dt_expected): for fmt in ('{:04d}-{:03d}', '{:04d}{:03d}'): dtstr = fmt.format(*isoord) assert isoparse(dtstr) == dt_expected ### # Acceptance of bytes @pytest.mark.parametrize('isostr,dt', [ (b'2014', datetime(2014, 1, 1)), (b'20140204', datetime(2014, 2, 4)), (b'2014-02-04', datetime(2014, 2, 4)), (b'2014-02-04T12', datetime(2014, 2, 4, 12)), (b'2014-02-04T12:30', datetime(2014, 2, 4, 12, 30)), (b'2014-02-04T12:30:15', datetime(2014, 2, 4, 12, 30, 15)), (b'2014-02-04T12:30:15.224', datetime(2014, 2, 4, 12, 30, 15, 224000)), (b'20140204T123015.224', datetime(2014, 2, 4, 12, 30, 15, 224000)), (b'2014-02-04T12:30:15.224Z', datetime(2014, 2, 4, 12, 30, 15, 224000, UTC)), (b'2014-02-04T12:30:15.224z', datetime(2014, 2, 4, 12, 30, 15, 224000, UTC)), (b'2014-02-04T12:30:15.224+05:00', datetime(2014, 2, 4, 12, 30, 15, 224000, tzinfo=tz.tzoffset(None, timedelta(hours=5))))]) def test_bytes(isostr, dt): assert isoparse(isostr) == dt ### # Invalid ISO strings @pytest.mark.parametrize( "isostr,exception", [ ("201", ValueError), # ISO string too short ("2012-0425", ValueError), # Inconsistent date separators ("201204-25", ValueError), # Inconsistent date separators ("20120425T0120:00", ValueError), # Inconsistent time separators ("20120425T01:2000", ValueError), # Inconsistent time separators ("14:3015", ValueError), # Inconsistent time separator ("20120425T012500-334", ValueError), # Wrong microsecond separator ("2001-1", ValueError), # YYYY-M not valid ("2012-04-9", ValueError), # YYYY-MM-D not valid ("201204", ValueError), # YYYYMM not valid ("20120411T03:30+", ValueError), # Time zone too short ("20120411T03:30+1234567", ValueError), # Time zone too long ("20120411T03:30-25:40", ValueError), # Time zone invalid ("2012-1a", ValueError), # Invalid month ("20120411T03:30+00:60", ValueError), # Time zone invalid minutes ("20120411T03:30+00:61", ValueError), # Time zone invalid minutes ("20120411T033030.123456012:00", ValueError), # No sign in time zone ("2012-W00", ValueError), # Invalid ISO week ("2012-W55", ValueError), # Invalid ISO week ("2012-W01-0", ValueError), # Invalid ISO week day ("2012-W01-8", ValueError), # Invalid ISO week day ("2013-000", ValueError), # Invalid ordinal day ("2013-366", ValueError), # Invalid ordinal day ("2013366", ValueError), # Invalid ordinal day ("2014-03-12Т12:30:14", ValueError), # Cyrillic T ("2014-04-21T24:00:01", ValueError), # Invalid use of 24 for midnight ("2014_W01-1", ValueError), # Invalid separator ("2014W01-1", ValueError), # Inconsistent use of dashes ("2014-W011", ValueError), # Inconsistent use of dashes ("20200728121240", ValueError), # Seconds too short ], ) def test_iso_raises(isostr, exception): with pytest.raises(exception): isoparse(isostr) @pytest.mark.parametrize('sep_act, valid_sep, exception', [ ('T', 'C', ValueError), ('C', 'T', ValueError), ]) def test_iso_with_sep_raises(sep_act, valid_sep, exception): parser = isoparser(sep=valid_sep) isostr = '2012-04-25' + sep_act + '01:25:00' with pytest.raises(exception): parser.isoparse(isostr) ### # Test ISOParser constructor @pytest.mark.parametrize('sep', [' ', '9', 'ðŸ�›']) def test_isoparser_invalid_sep(sep): with pytest.raises(ValueError): isoparser(sep=sep) @pytest.mark.xfail( reason="Bytes separators are not supported", raises=TypeError ) def test_isoparser_byte_sep(): dt = datetime(2017, 12, 6, 12, 30, 45) dt_str = dt.isoformat(sep="T") dt_rt = isoparser(sep=b'T').isoparse(dt_str) assert dt == dt_rt ### # Test parse_tzstr @pytest.mark.parametrize('tzoffset', FULL_TZOFFSETS) def test_parse_tzstr(tzoffset): dt = datetime(2017, 11, 27, 6, 14, 30, 123456) date_fmt = '%Y-%m-%d' time_fmt = '%H:%M:%S.%f' _isoparse_date_and_time(dt, date_fmt, time_fmt, tzoffset) @pytest.mark.parametrize('tzstr', [ '-00:00', '+00:00', '+00', '-00', '+0000', '-0000' ]) @pytest.mark.parametrize('zero_as_utc', [True, False]) def test_parse_tzstr_zero_as_utc(tzstr, zero_as_utc): tzi = isoparser().parse_tzstr(tzstr, zero_as_utc=zero_as_utc) assert tzi == UTC assert (type(tzi) == tz.tzutc) == zero_as_utc @pytest.mark.parametrize( "tzstr,exception", [ ("00:00", ValueError), # No sign ("05:00", ValueError), # No sign ("_00:00", ValueError), # Invalid sign ("+25:00", ValueError), # Offset too large ("00:0000", ValueError), # String too long ("+01:0", ValueError), # Minutes too short ("+01000", ValueError), # Minutes too long ("+ 1:00", ValueError), # Whitespace in hours ("+-1:00", ValueError), # Sign in hours ("+01:-5", ValueError), # Sign in minutes ], ) def test_parse_tzstr_fails(tzstr, exception): with pytest.raises(exception): isoparser().parse_tzstr(tzstr) ### # Test parse_isodate def __make_date_examples(): dates_no_day = [ date(1999, 12, 1), date(2016, 2, 1) ] dates_no_day.append(date(1000, 11, 1)) # Only one supported format for dates with no day o = zip(dates_no_day, it.repeat('%Y-%m')) dates_w_day = [ date(1969, 12, 31), date(1900, 1, 1), date(2016, 2, 29), date(2017, 11, 14) ] dates_w_day_fmts = ('%Y%m%d', '%Y-%m-%d') o = it.chain(o, it.product(dates_w_day, dates_w_day_fmts)) return list(o) @pytest.mark.parametrize('d,dt_fmt', __make_date_examples()) @pytest.mark.parametrize('as_bytes', [True, False]) def test_parse_isodate(d, dt_fmt, as_bytes): d_str = d.strftime(dt_fmt) if as_bytes: d_str = d_str.encode('ascii') iparser = isoparser() assert iparser.parse_isodate(d_str) == d @pytest.mark.parametrize( "isostr,exception", [ ("243", ValueError), # ISO string too short ("2014-0423", ValueError), # Inconsistent date separators ("201404-23", ValueError), # Inconsistent date separators ("2014æ—¥03月14", ValueError), # Not ASCII ("2013-02-29", ValueError), # Not a leap year ("2014/12/03", ValueError), # Wrong separators ("2014-04-19T", ValueError), # Unknown components ("201202", ValueError), # Invalid format ("2014-W1", ValueError), # ISO week too short ("2_14-04-21", ValueError), # Underscore in year ("+014-04-21", ValueError), # Sign in year ("2014- 4-21", ValueError), # Whitespace in month ("2014-04-2 ", ValueError), # Whitespace in day ("2014- 10", ValueError), # Whitespace in ordinal day ("2014-W1 -1", ValueError), # Whitespace in ISO week ], ) def test_isodate_raises(isostr, exception): with pytest.raises(exception): isoparser().parse_isodate(isostr) def test_parse_isodate_error_text(): with pytest.raises(ValueError) as excinfo: isoparser().parse_isodate('2014-0423') # ensure the error message does not contain b' prefixes expected_error = "String contains unknown ISO components: '2014-0423'" assert expected_error == str(excinfo.value) ### # Test parse_isotime def __make_time_examples(): outputs = [] # HH time_h = [time(0), time(8), time(22)] time_h_fmts = ['%H'] outputs.append(it.product(time_h, time_h_fmts)) # HHMM / HH:MM time_hm = [time(0, 0), time(0, 30), time(8, 47), time(16, 1)] time_hm_fmts = ['%H%M', '%H:%M'] outputs.append(it.product(time_hm, time_hm_fmts)) # HHMMSS / HH:MM:SS time_hms = [time(0, 0, 0), time(0, 15, 30), time(8, 2, 16), time(12, 0), time(16, 2), time(20, 45)] time_hms_fmts = ['%H%M%S', '%H:%M:%S'] outputs.append(it.product(time_hms, time_hms_fmts)) # HHMMSS.ffffff / HH:MM:SS.ffffff time_hmsu = [time(0, 0, 0, 0), time(4, 15, 3, 247993), time(14, 21, 59, 948730), time(23, 59, 59, 999999)] time_hmsu_fmts = ['%H%M%S.%f', '%H:%M:%S.%f'] outputs.append(it.product(time_hmsu, time_hmsu_fmts)) outputs = list(map(list, outputs)) # Time zones ex_naive = list(it.chain.from_iterable(x[0:2] for x in outputs)) o = it.product(ex_naive, TZOFFSETS) # ((time, fmt), (tzinfo, offsetstr)) o = ((t.replace(tzinfo=tzi), fmt + off_str) for (t, fmt), (tzi, off_str) in o) outputs.append(o) return list(it.chain.from_iterable(outputs)) @pytest.mark.parametrize('time_val,time_fmt', __make_time_examples()) @pytest.mark.parametrize('as_bytes', [True, False]) def test_isotime(time_val, time_fmt, as_bytes): tstr = time_val.strftime(time_fmt) if as_bytes: tstr = tstr.encode('ascii') iparser = isoparser() assert iparser.parse_isotime(tstr) == time_val @pytest.mark.parametrize('isostr', [ '24:00', '2400', '24:00:00', '240000', '24:00:00.000', '24:00:00,000', '24:00:00.000000', '24:00:00,000000', ]) def test_isotime_midnight(isostr): iparser = isoparser() assert iparser.parse_isotime(isostr) == time(0, 0, 0, 0) @pytest.mark.parametrize( "isostr,exception", [ ("3", ValueError), # ISO string too short ("14時30分15ç§’", ValueError), # Not ASCII ("14_30_15", ValueError), # Invalid separators ("1430:15", ValueError), # Inconsistent separator use ("25", ValueError), # Invalid hours ("25:15", ValueError), # Invalid hours ("14:60", ValueError), # Invalid minutes ("14:59:61", ValueError), # Invalid seconds ("14:30:15.34468305:00", ValueError), # No sign in time zone ("14:30:15+", ValueError), # Time zone too short ("14:30:15+1234567", ValueError), # Time zone invalid ("14:59:59+25:00", ValueError), # Invalid tz hours ("14:59:59+12:62", ValueError), # Invalid tz minutes ("14:59:30_344583", ValueError), # Invalid microsecond separator ("24:01", ValueError), # 24 used for non-midnight time ("24:00:01", ValueError), # 24 used for non-midnight time ("24:00:00.001", ValueError), # 24 used for non-midnight time ("24:00:00.000001", ValueError), # 24 used for non-midnight time ("14:3", ValueError), # Minutes too short ("14:30:1", ValueError), # Seconds too short ("1 :30", ValueError), # Whitespace in hours ("12:+5", ValueError), # Sign in minutes ("12:30: 5", ValueError), # Whitespace in seconds ], ) def test_isotime_raises(isostr, exception): iparser = isoparser() with pytest.raises(exception): iparser.parse_isotime(isostr) python_dateutil-4.0.0/tests/test_parser.py0000644000000000000000000011212513615410400015720 0ustar00import itertools import sys import unittest from datetime import datetime, timedelta from io import StringIO import pytest from dateutil import tz from dateutil.parser import ( ParserError, UnknownTimezoneWarning, parse, parserinfo, ) from dateutil.tz import tzoffset from ._common import TZEnvContext # Platform info IS_WIN = sys.platform.startswith('win') PLATFORM_HAS_DASH_D = False try: if datetime.now().strftime('%-d'): PLATFORM_HAS_DASH_D = True except ValueError: pass @pytest.fixture(params=[True, False]) def fuzzy(request): """Fixture to pass fuzzy=True or fuzzy=False to parse""" return request.param # Parser test cases using no keyword arguments. Format: (parsable_text, expected_datetime, assertion_message) PARSER_TEST_CASES = [ ("Thu Sep 25 10:36:28 2003", datetime(2003, 9, 25, 10, 36, 28), "date command format strip"), ("Thu Sep 25 2003", datetime(2003, 9, 25), "date command format strip"), ("2003-09-25T10:49:41", datetime(2003, 9, 25, 10, 49, 41), "iso format strip"), ("2003-09-25T10:49", datetime(2003, 9, 25, 10, 49), "iso format strip"), ("2003-09-25T10", datetime(2003, 9, 25, 10), "iso format strip"), ("2003-09-25", datetime(2003, 9, 25), "iso format strip"), ("20030925T104941", datetime(2003, 9, 25, 10, 49, 41), "iso stripped format strip"), ("20030925T1049", datetime(2003, 9, 25, 10, 49, 0), "iso stripped format strip"), ("20030925T10", datetime(2003, 9, 25, 10), "iso stripped format strip"), ("20030925", datetime(2003, 9, 25), "iso stripped format strip"), ("2003-09-25 10:49:41,502", datetime(2003, 9, 25, 10, 49, 41, 502000), "python logger format"), ("199709020908", datetime(1997, 9, 2, 9, 8), "no separator"), ("19970902090807", datetime(1997, 9, 2, 9, 8, 7), "no separator"), ("09-25-2003", datetime(2003, 9, 25), "date with dash"), ("25-09-2003", datetime(2003, 9, 25), "date with dash"), ("10-09-2003", datetime(2003, 10, 9), "date with dash"), ("10-09-03", datetime(2003, 10, 9), "date with dash"), ("2003.09.25", datetime(2003, 9, 25), "date with dot"), ("09.25.2003", datetime(2003, 9, 25), "date with dot"), ("25.09.2003", datetime(2003, 9, 25), "date with dot"), ("10.09.2003", datetime(2003, 10, 9), "date with dot"), ("10.09.03", datetime(2003, 10, 9), "date with dot"), ("2003/09/25", datetime(2003, 9, 25), "date with slash"), ("09/25/2003", datetime(2003, 9, 25), "date with slash"), ("25/09/2003", datetime(2003, 9, 25), "date with slash"), ("10/09/2003", datetime(2003, 10, 9), "date with slash"), ("10/09/03", datetime(2003, 10, 9), "date with slash"), ("2003 09 25", datetime(2003, 9, 25), "date with space"), ("09 25 2003", datetime(2003, 9, 25), "date with space"), ("25 09 2003", datetime(2003, 9, 25), "date with space"), ("10 09 2003", datetime(2003, 10, 9), "date with space"), ("10 09 03", datetime(2003, 10, 9), "date with space"), ("25 09 03", datetime(2003, 9, 25), "date with space"), ("03 25 Sep", datetime(2003, 9, 25), "strangely ordered date"), ("25 03 Sep", datetime(2025, 9, 3), "strangely ordered date"), (" July 4 , 1976 12:01:02 am ", datetime(1976, 7, 4, 0, 1, 2), "extra space"), ("Wed, July 10, '96", datetime(1996, 7, 10, 0, 0), "random format"), ("1996.July.10 AD 12:08 PM", datetime(1996, 7, 10, 12, 8), "random format"), ("July 4, 1976", datetime(1976, 7, 4), "random format"), ("7 4 1976", datetime(1976, 7, 4), "random format"), ("4 jul 1976", datetime(1976, 7, 4), "random format"), ("4 Jul 1976", datetime(1976, 7, 4), "'%-d %b %Y' format"), ("7-4-76", datetime(1976, 7, 4), "random format"), ("19760704", datetime(1976, 7, 4), "random format"), ("0:01:02 on July 4, 1976", datetime(1976, 7, 4, 0, 1, 2), "random format"), ("July 4, 1976 12:01:02 am", datetime(1976, 7, 4, 0, 1, 2), "random format"), ("Mon Jan 2 04:24:27 1995", datetime(1995, 1, 2, 4, 24, 27), "random format"), ("04.04.95 00:22", datetime(1995, 4, 4, 0, 22), "random format"), ("Jan 1 1999 11:23:34.578", datetime(1999, 1, 1, 11, 23, 34, 578000), "random format"), ("950404 122212", datetime(1995, 4, 4, 12, 22, 12), "random format"), ("3rd of May 2001", datetime(2001, 5, 3), "random format"), ("5th of March 2001", datetime(2001, 3, 5), "random format"), ("1st of May 2003", datetime(2003, 5, 1), "random format"), ('0099-01-01T00:00:00', datetime(99, 1, 1, 0, 0), "99 ad"), ('0031-01-01T00:00:00', datetime(31, 1, 1, 0, 0), "31 ad"), ("20080227T21:26:01.123456789", datetime(2008, 2, 27, 21, 26, 1, 123456), "high precision seconds"), ('13NOV2017', datetime(2017, 11, 13), "dBY (See GH360)"), ('0003-03-04', datetime(3, 3, 4), "pre 12 year same month (See GH PR #293)"), ('December.0031.30', datetime(31, 12, 30), "BYd corner case (GH#687)"), # Cases with legacy h/m/s format, candidates for deprecation (GH#886) ("2016-12-21 04.2h", datetime(2016, 12, 21, 4, 12), "Fractional Hours"), ] # Check that we don't have any duplicates assert len(set([x[0] for x in PARSER_TEST_CASES])) == len(PARSER_TEST_CASES) @pytest.mark.parametrize("parsable_text,expected_datetime,assertion_message", PARSER_TEST_CASES) def test_parser(parsable_text, expected_datetime, assertion_message): assert parse(parsable_text) == expected_datetime, assertion_message # Parser test cases using datetime(2003, 9, 25) as a default. # Format: (parsable_text, expected_datetime, assertion_message) PARSER_DEFAULT_TEST_CASES = [ ("Thu Sep 25 10:36:28", datetime(2003, 9, 25, 10, 36, 28), "date command format strip"), ("Thu Sep 10:36:28", datetime(2003, 9, 25, 10, 36, 28), "date command format strip"), ("Thu 10:36:28", datetime(2003, 9, 25, 10, 36, 28), "date command format strip"), ("Sep 10:36:28", datetime(2003, 9, 25, 10, 36, 28), "date command format strip"), ("10:36:28", datetime(2003, 9, 25, 10, 36, 28), "date command format strip"), ("10:36", datetime(2003, 9, 25, 10, 36), "date command format strip"), ("Sep 2003", datetime(2003, 9, 25), "date command format strip"), ("Sep", datetime(2003, 9, 25), "date command format strip"), ("2003", datetime(2003, 9, 25), "date command format strip"), ("10h36m28.5s", datetime(2003, 9, 25, 10, 36, 28, 500000), "hour with letters"), ("10h36m28s", datetime(2003, 9, 25, 10, 36, 28), "hour with letters strip"), ("10h36m", datetime(2003, 9, 25, 10, 36), "hour with letters strip"), ("10h", datetime(2003, 9, 25, 10), "hour with letters strip"), ("10 h 36", datetime(2003, 9, 25, 10, 36), "hour with letters strip"), ("10 h 36.5", datetime(2003, 9, 25, 10, 36, 30), "hour with letter strip"), ("36 m 5", datetime(2003, 9, 25, 0, 36, 5), "hour with letters spaces"), ("36 m 5 s", datetime(2003, 9, 25, 0, 36, 5), "minute with letters spaces"), ("36 m 05", datetime(2003, 9, 25, 0, 36, 5), "minute with letters spaces"), ("36 m 05 s", datetime(2003, 9, 25, 0, 36, 5), "minutes with letters spaces"), ("10h am", datetime(2003, 9, 25, 10), "hour am pm"), ("10h pm", datetime(2003, 9, 25, 22), "hour am pm"), ("10am", datetime(2003, 9, 25, 10), "hour am pm"), ("10pm", datetime(2003, 9, 25, 22), "hour am pm"), ("10:00 am", datetime(2003, 9, 25, 10), "hour am pm"), ("10:00 pm", datetime(2003, 9, 25, 22), "hour am pm"), ("10:00am", datetime(2003, 9, 25, 10), "hour am pm"), ("10:00pm", datetime(2003, 9, 25, 22), "hour am pm"), ("10:00a.m", datetime(2003, 9, 25, 10), "hour am pm"), ("10:00p.m", datetime(2003, 9, 25, 22), "hour am pm"), ("10:00a.m.", datetime(2003, 9, 25, 10), "hour am pm"), ("10:00p.m.", datetime(2003, 9, 25, 22), "hour am pm"), ("Wed", datetime(2003, 10, 1), "weekday alone"), ("Wednesday", datetime(2003, 10, 1), "long weekday"), ("October", datetime(2003, 10, 25), "long month"), ("31-Dec-00", datetime(2000, 12, 31), "zero year"), ("0:01:02", datetime(2003, 9, 25, 0, 1, 2), "random format"), ("12h 01m02s am", datetime(2003, 9, 25, 0, 1, 2), "random format"), ("12:08 PM", datetime(2003, 9, 25, 12, 8), "random format"), ("01h02m03", datetime(2003, 9, 25, 1, 2, 3), "random format"), ("01h02", datetime(2003, 9, 25, 1, 2), "random format"), ("01h02s", datetime(2003, 9, 25, 1, 0, 2), "random format"), ("01m02", datetime(2003, 9, 25, 0, 1, 2), "random format"), ("01m02h", datetime(2003, 9, 25, 2, 1), "random format"), ("2004 10 Apr 11h30m", datetime(2004, 4, 10, 11, 30), "random format") ] # Check that we don't have any duplicates assert len(set([x[0] for x in PARSER_DEFAULT_TEST_CASES])) == len(PARSER_DEFAULT_TEST_CASES) @pytest.mark.parametrize("parsable_text,expected_datetime,assertion_message", PARSER_DEFAULT_TEST_CASES) def test_parser_default(parsable_text, expected_datetime, assertion_message): assert parse(parsable_text, default=datetime(2003, 9, 25)) == expected_datetime, assertion_message @pytest.mark.parametrize('sep', ['-', '.', '/', ' ']) def test_parse_dayfirst(sep): expected = datetime(2003, 9, 10) fmt = sep.join(['%d', '%m', '%Y']) dstr = expected.strftime(fmt) result = parse(dstr, dayfirst=True) assert result == expected @pytest.mark.parametrize('sep', ['-', '.', '/', ' ']) def test_parse_yearfirst(sep): expected = datetime(2010, 9, 3) fmt = sep.join(['%Y', '%m', '%d']) dstr = expected.strftime(fmt) result = parse(dstr, yearfirst=True) assert result == expected @pytest.mark.parametrize('dstr,expected', [ ("Thu Sep 25 10:36:28 BRST 2003", datetime(2003, 9, 25, 10, 36, 28)), ("1996.07.10 AD at 15:08:56 PDT", datetime(1996, 7, 10, 15, 8, 56)), ("Tuesday, April 12, 1952 AD 3:30:42pm PST", datetime(1952, 4, 12, 15, 30, 42)), ("November 5, 1994, 8:15:30 am EST", datetime(1994, 11, 5, 8, 15, 30)), ("1994-11-05T08:15:30-05:00", datetime(1994, 11, 5, 8, 15, 30)), ("1994-11-05T08:15:30Z", datetime(1994, 11, 5, 8, 15, 30)), ("1976-07-04T00:01:02Z", datetime(1976, 7, 4, 0, 1, 2)), ("1986-07-05T08:15:30z", datetime(1986, 7, 5, 8, 15, 30)), ("Tue Apr 4 00:22:12 PDT 1995", datetime(1995, 4, 4, 0, 22, 12)), ]) def test_parse_ignoretz(dstr, expected): result = parse(dstr, ignoretz=True) assert result == expected _brsttz = tzoffset("BRST", -10800) @pytest.mark.parametrize('dstr,expected', [ ("20030925T104941-0300", datetime(2003, 9, 25, 10, 49, 41, tzinfo=_brsttz)), ("Thu, 25 Sep 2003 10:49:41 -0300", datetime(2003, 9, 25, 10, 49, 41, tzinfo=_brsttz)), ("2003-09-25T10:49:41.5-03:00", datetime(2003, 9, 25, 10, 49, 41, 500000, tzinfo=_brsttz)), ("2003-09-25T10:49:41-03:00", datetime(2003, 9, 25, 10, 49, 41, tzinfo=_brsttz)), ("20030925T104941.5-0300", datetime(2003, 9, 25, 10, 49, 41, 500000, tzinfo=_brsttz)), ]) def test_parse_with_tzoffset(dstr, expected): # In these cases, we are _not_ passing a tzinfos arg result = parse(dstr) assert result == expected class TestFormat: def test_ybd(self): # If we have a 4-digit year, a non-numeric month (abbreviated or not), # and a day (1 or 2 digits), then there is no ambiguity as to which # token is a year/month/day. This holds regardless of what order the # terms are in and for each of the separators below. seps = ['-', ' ', '/', '.'] year_tokens = ['%Y'] month_tokens = ['%b', '%B'] day_tokens = ['%d'] if PLATFORM_HAS_DASH_D: day_tokens.append('%-d') prods = itertools.product(year_tokens, month_tokens, day_tokens) perms = [y for x in prods for y in itertools.permutations(x)] unambig_fmts = [sep.join(perm) for sep in seps for perm in perms] actual = datetime(2003, 9, 25) for fmt in unambig_fmts: dstr = actual.strftime(fmt) res = parse(dstr) assert res == actual # TODO: some redundancy with PARSER_TEST_CASES cases @pytest.mark.parametrize("fmt,dstr", [ ("%a %b %d %Y", "Thu Sep 25 2003"), ("%b %d %Y", "Sep 25 2003"), ("%Y-%m-%d", "2003-09-25"), ("%Y%m%d", "20030925"), ("%Y-%b-%d", "2003-Sep-25"), ("%d-%b-%Y", "25-Sep-2003"), ("%b-%d-%Y", "Sep-25-2003"), ("%m-%d-%Y", "09-25-2003"), ("%d-%m-%Y", "25-09-2003"), ("%Y.%m.%d", "2003.09.25"), ("%Y.%b.%d", "2003.Sep.25"), ("%d.%b.%Y", "25.Sep.2003"), ("%b.%d.%Y", "Sep.25.2003"), ("%m.%d.%Y", "09.25.2003"), ("%d.%m.%Y", "25.09.2003"), ("%Y/%m/%d", "2003/09/25"), ("%Y/%b/%d", "2003/Sep/25"), ("%d/%b/%Y", "25/Sep/2003"), ("%b/%d/%Y", "Sep/25/2003"), ("%m/%d/%Y", "09/25/2003"), ("%d/%m/%Y", "25/09/2003"), ("%Y %m %d", "2003 09 25"), ("%Y %b %d", "2003 Sep 25"), ("%d %b %Y", "25 Sep 2003"), ("%m %d %Y", "09 25 2003"), ("%d %m %Y", "25 09 2003"), ("%y %d %b", "03 25 Sep",), ]) def test_strftime_formats_2003Sep25(self, fmt, dstr): expected = datetime(2003, 9, 25) # First check that the format strings behave as expected # (not strictly necessary, but nice to have) assert expected.strftime(fmt) == dstr res = parse(dstr) assert res == expected class TestInputTypes: def test_empty_string_invalid(self): with pytest.raises(ParserError): parse('') def test_none_invalid(self): with pytest.raises(TypeError): parse(None) def test_int_invalid(self): with pytest.raises(TypeError): parse(13) def test_duck_typing(self): # We want to support arbitrary classes that implement the stream # interface. class StringPassThrough: def __init__(self, stream): self.stream = stream def read(self, *args, **kwargs): return self.stream.read(*args, **kwargs) dstr = StringPassThrough(StringIO('2014 January 19')) res = parse(dstr) expected = datetime(2014, 1, 19) assert res == expected def test_parse_stream(self): dstr = StringIO('2014 January 19') res = parse(dstr) expected = datetime(2014, 1, 19) assert res == expected def test_parse_str(self): # Parser should be able to handle bytestring and unicode uni_str = '2014-05-01 08:00:00' bytes_str = uni_str.encode() res = parse(bytes_str) expected = parse(uni_str) assert res == expected def test_parse_bytes(self): res = parse(b'2014 January 19') expected = datetime(2014, 1, 19) assert res == expected def test_parse_bytearray(self): # GH#417 res = parse(bytearray(b'2014 January 19')) expected = datetime(2014, 1, 19) assert res == expected class TestTzinfoInputTypes: def assert_equal_same_tz(self, dt1, dt2): assert dt1 == dt2 assert dt1.tzinfo is dt2.tzinfo def test_tzinfo_dict_could_return_none(self): dstr = "2017-02-03 12:40 BRST" result = parse(dstr, tzinfos={"BRST": None}) expected = datetime(2017, 2, 3, 12, 40) self.assert_equal_same_tz(result, expected) def test_tzinfos_callable_could_return_none(self): dstr = "2017-02-03 12:40 BRST" result = parse(dstr, tzinfos=lambda *args: None) expected = datetime(2017, 2, 3, 12, 40) self.assert_equal_same_tz(result, expected) def test_invalid_tzinfo_input(self): dstr = "2014 January 19 09:00 UTC" # Pass an absurd tzinfos object tzinfos = {"UTC": ValueError} with pytest.raises(TypeError): parse(dstr, tzinfos=tzinfos) def test_valid_tzinfo_tzinfo_input(self): dstr = "2014 January 19 09:00 UTC" tzinfos = {"UTC": tz.UTC} expected = datetime(2014, 1, 19, 9, tzinfo=tz.UTC) res = parse(dstr, tzinfos=tzinfos) self.assert_equal_same_tz(res, expected) def test_valid_tzinfo_unicode_input(self): dstr = "2014 January 19 09:00 UTC" tzinfos = {"UTC": "UTC+0"} expected = datetime(2014, 1, 19, 9, tzinfo=tz.tzstr("UTC+0")) res = parse(dstr, tzinfos=tzinfos) self.assert_equal_same_tz(res, expected) def test_valid_tzinfo_callable_input(self): dstr = "2014 January 19 09:00 UTC" def tzinfos(*args, **kwargs): return "UTC+0" expected = datetime(2014, 1, 19, 9, tzinfo=tz.tzstr("UTC+0")) res = parse(dstr, tzinfos=tzinfos) self.assert_equal_same_tz(res, expected) def test_valid_tzinfo_int_input(self): dstr = "2014 January 19 09:00 UTC" tzinfos = {"UTC": -28800} expected = datetime(2014, 1, 19, 9, tzinfo=tz.tzoffset("UTC", -28800)) res = parse(dstr, tzinfos=tzinfos) self.assert_equal_same_tz(res, expected) class ParserTest(unittest.TestCase): @classmethod def setup_class(cls): cls.tzinfos = {"BRST": -10800} cls.brsttz = tzoffset("BRST", -10800) cls.default = datetime(2003, 9, 25) # Parser should be able to handle bytestring and unicode cls.uni_str = '2014-05-01 08:00:00' cls.str_str = cls.uni_str.encode() def testParserParseStr(self): from dateutil.parser import parser assert parser().parse(self.str_str) == parser().parse(self.uni_str) def testParseUnicodeWords(self): class rus_parserinfo(parserinfo): MONTHS = [("Ñ�нв", "Январь"), ("фев", "Февраль"), ("мар", "Март"), ("апр", "Ð�прель"), ("май", "Май"), ("июн", "Июнь"), ("июл", "Июль"), ("авг", "Ð�вгуÑ�Ñ‚"), ("Ñ�ен", "СентÑ�брь"), ("окт", "ОктÑ�брь"), ("ноÑ�", "Ð�оÑ�брь"), ("дек", "Декабрь")] expected = datetime(2015, 9, 10, 10, 20) res = parse('10 СентÑ�брь 2015 10:20', parserinfo=rus_parserinfo()) assert res == expected def testParseWithNulls(self): pstring = '\x00\x00August 29, 1924' assert parse(pstring) == datetime(1924, 8, 29) def testDateCommandFormat(self): self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003", tzinfos=self.tzinfos), datetime(2003, 9, 25, 10, 36, 28, tzinfo=self.brsttz)) def testDateCommandFormatReversed(self): self.assertEqual(parse("2003 10:36:28 BRST 25 Sep Thu", tzinfos=self.tzinfos), datetime(2003, 9, 25, 10, 36, 28, tzinfo=self.brsttz)) def testISOFormatStrip2(self): self.assertEqual(parse("2003-09-25T10:49:41+03:00"), datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, 10800))) def testISOStrippedFormatStrip2(self): self.assertEqual(parse("20030925T104941+0300"), datetime(2003, 9, 25, 10, 49, 41, tzinfo=tzoffset(None, 10800))) def testAMPMNoHour(self): with pytest.raises(ParserError): parse("AM") with pytest.raises(ParserError): parse("Jan 20, 2015 PM") def testAMPMRange(self): with pytest.raises(ParserError): parse("13:44 AM") with pytest.raises(ParserError): parse("January 25, 1921 23:13 PM") def testPertain(self): self.assertEqual(parse("Sep 03", default=self.default), datetime(2003, 9, 3)) self.assertEqual(parse("Sep of 03", default=self.default), datetime(2003, 9, 25)) def testFuzzy(self): s = "Today is 25 of September of 2003, exactly " \ "at 10:49:41 with timezone -03:00." self.assertEqual(parse(s, fuzzy=True), datetime(2003, 9, 25, 10, 49, 41, tzinfo=self.brsttz)) def testFuzzyWithTokens(self): s1 = "Today is 25 of September of 2003, exactly " \ "at 10:49:41 with timezone -03:00." self.assertEqual(parse(s1, fuzzy_with_tokens=True), (datetime(2003, 9, 25, 10, 49, 41, tzinfo=self.brsttz), ('Today is ', 'of ', ', exactly at ', ' with timezone ', '.'))) s2 = "http://biz.yahoo.com/ipo/p/600221.html" self.assertEqual(parse(s2, fuzzy_with_tokens=True), (datetime(2060, 2, 21, 0, 0, 0), ('http://biz.yahoo.com/ipo/p/', '.html'))) def testFuzzyAMPMProblem(self): # Sometimes fuzzy parsing results in AM/PM flag being set without # hours - if it's fuzzy it should ignore that. s1 = "I have a meeting on March 1, 1974." s2 = "On June 8th, 2020, I am going to be the first man on Mars" # Also don't want any erroneous AM or PMs changing the parsed time s3 = "Meet me at the AM/PM on Sunset at 3:00 AM on December 3rd, 2003" s4 = "Meet me at 3:00AM on December 3rd, 2003 at the AM/PM on Sunset" self.assertEqual(parse(s1, fuzzy=True), datetime(1974, 3, 1)) self.assertEqual(parse(s2, fuzzy=True), datetime(2020, 6, 8)) self.assertEqual(parse(s3, fuzzy=True), datetime(2003, 12, 3, 3)) self.assertEqual(parse(s4, fuzzy=True), datetime(2003, 12, 3, 3)) def testFuzzyIgnoreAMPM(self): s1 = "Jan 29, 1945 14:45 AM I going to see you there?" with pytest.warns(UnknownTimezoneWarning): res = parse(s1, fuzzy=True) self.assertEqual(res, datetime(1945, 1, 29, 14, 45)) def testRandomFormat24(self): self.assertEqual(parse("0:00 PM, PST", default=self.default, ignoretz=True), datetime(2003, 9, 25, 12, 0)) def testRandomFormat26(self): with pytest.warns(UnknownTimezoneWarning): res = parse("5:50 A.M. on June 13, 1990") self.assertEqual(res, datetime(1990, 6, 13, 5, 50)) def testUnspecifiedDayFallback(self): # Test that for an unspecified day, the fallback behavior is correct. self.assertEqual(parse("April 2009", default=datetime(2010, 1, 31)), datetime(2009, 4, 30)) def testUnspecifiedDayFallbackFebNoLeapYear(self): self.assertEqual(parse("Feb 2007", default=datetime(2010, 1, 31)), datetime(2007, 2, 28)) def testUnspecifiedDayFallbackFebLeapYear(self): self.assertEqual(parse("Feb 2008", default=datetime(2010, 1, 31)), datetime(2008, 2, 29)) def testErrorType01(self): with pytest.raises(ParserError): parse('shouldfail') def testCorrectErrorOnFuzzyWithTokens(self): self.assertRaisesRegex( ParserError, "Unknown string format", parse, "04/04/32/423", fuzzy_with_tokens=True, ) self.assertRaisesRegex( ParserError, "Unknown string format", parse, "04/04/04 +32423", fuzzy_with_tokens=True, ) self.assertRaisesRegex( ParserError, "Unknown string format", parse, "04/04/0d4", fuzzy_with_tokens=True, ) def testIncreasingCTime(self): # This test will check 200 different years, every month, every day, # every hour, every minute, every second, and every weekday, using # a delta of more or less 1 year, 1 month, 1 day, 1 minute and # 1 second. delta = timedelta(days=365+31+1, seconds=1+60+60*60) dt = datetime(1900, 1, 1, 0, 0, 0, 0) for i in range(200): assert parse(dt.ctime()) == dt dt += delta def testIncreasingISOFormat(self): delta = timedelta(days=365+31+1, seconds=1+60+60*60) dt = datetime(1900, 1, 1, 0, 0, 0, 0) for i in range(200): assert parse(dt.isoformat()) == dt dt += delta def testMicrosecondsPrecisionError(self): # Skip found out that sad precision problem. :-( dt1 = parse("00:11:25.01") dt2 = parse("00:12:10.01") assert dt1.microsecond == 10000 assert dt2.microsecond == 10000 def testMicrosecondPrecisionErrorReturns(self): # One more precision issue, discovered by Eric Brown. This should # be the last one, as we're no longer using floating points. for ms in [100001, 100000, 99999, 99998, 10001, 10000, 9999, 9998, 1001, 1000, 999, 998, 101, 100, 99, 98]: dt = datetime(2008, 2, 27, 21, 26, 1, ms) assert parse(dt.isoformat()) == dt def testCustomParserInfo(self): # Custom parser info wasn't working, as Michael Elsdörfer discovered. from dateutil.parser import parser, parserinfo class myparserinfo(parserinfo): MONTHS = parserinfo.MONTHS[:] MONTHS[0] = ("Foo", "Foo") myparser = parser(myparserinfo()) dt = myparser.parse("01/Foo/2007") assert dt == datetime(2007, 1, 1) def testCustomParserShortDaynames(self): # Horacio Hoyos discovered that day names shorter than 3 characters, # for example two letter German day name abbreviations, don't work: # https://github.com/dateutil/dateutil/issues/343 from dateutil.parser import parser, parserinfo class GermanParserInfo(parserinfo): WEEKDAYS = [("Mo", "Montag"), ("Di", "Dienstag"), ("Mi", "Mittwoch"), ("Do", "Donnerstag"), ("Fr", "Freitag"), ("Sa", "Samstag"), ("So", "Sonntag")] myparser = parser(GermanParserInfo()) dt = myparser.parse("Sa 21. Jan 2017") self.assertEqual(dt, datetime(2017, 1, 21)) def testNoYearFirstNoDayFirst(self): dtstr = '090107' # Should be MMDDYY self.assertEqual(parse(dtstr), datetime(2007, 9, 1)) self.assertEqual(parse(dtstr, yearfirst=False, dayfirst=False), datetime(2007, 9, 1)) def testYearFirst(self): dtstr = '090107' # Should be MMDDYY self.assertEqual(parse(dtstr, yearfirst=True), datetime(2009, 1, 7)) self.assertEqual(parse(dtstr, yearfirst=True, dayfirst=False), datetime(2009, 1, 7)) def testDayFirst(self): dtstr = '090107' # Should be DDMMYY self.assertEqual(parse(dtstr, dayfirst=True), datetime(2007, 1, 9)) self.assertEqual(parse(dtstr, yearfirst=False, dayfirst=True), datetime(2007, 1, 9)) def testDayFirstYearFirst(self): dtstr = '090107' # Should be YYDDMM self.assertEqual(parse(dtstr, yearfirst=True, dayfirst=True), datetime(2009, 7, 1)) def testUnambiguousYearFirst(self): dtstr = '2015 09 25' self.assertEqual(parse(dtstr, yearfirst=True), datetime(2015, 9, 25)) def testUnambiguousDayFirst(self): dtstr = '2015 09 25' self.assertEqual(parse(dtstr, dayfirst=True), datetime(2015, 9, 25)) def testUnambiguousDayFirstYearFirst(self): dtstr = '2015 09 25' self.assertEqual(parse(dtstr, dayfirst=True, yearfirst=True), datetime(2015, 9, 25)) def test_mstridx(self): # See GH408 dtstr = '2015-15-May' self.assertEqual(parse(dtstr), datetime(2015, 5, 15)) def test_idx_check(self): dtstr = '2017-07-17 06:15:' # Pre-PR, the trailing colon will cause an IndexError at 824-825 # when checking `i < len_l` and then accessing `l[i+1]` res = parse(dtstr, fuzzy=True) assert res == datetime(2017, 7, 17, 6, 15) def test_hmBY(self): # See GH#483 dtstr = '02:17NOV2017' res = parse(dtstr, default=self.default) assert res == datetime(2017, 11, self.default.day, 2, 17) def test_validate_hour(self): # See GH353 invalid = "201A-01-01T23:58:39.239769+03:00" with pytest.raises(ParserError): parse(invalid) def test_era_trailing_year(self): dstr = 'AD2001' res = parse(dstr) assert res.year == 2001, res def test_includes_timestr(self): timestr = "2020-13-97T44:61:83" try: parse(timestr) except ParserError as e: assert e.args[1] == timestr else: pytest.fail("Failed to raise ParserError") class TestOutOfBounds: def test_no_year_zero(self): with pytest.raises(ParserError): parse("0000 Jun 20") def test_out_of_bound_day(self): with pytest.raises(ParserError): parse("Feb 30, 2007") def test_illegal_month_error(self): with pytest.raises(ParserError): parse("0-100") def test_day_sanity(self, fuzzy): dstr = "2014-15-25" with pytest.raises(ParserError): parse(dstr, fuzzy=fuzzy) def test_minute_sanity(self, fuzzy): dstr = "2014-02-28 22:64" with pytest.raises(ParserError): parse(dstr, fuzzy=fuzzy) def test_hour_sanity(self, fuzzy): dstr = "2014-02-28 25:16 PM" with pytest.raises(ParserError): parse(dstr, fuzzy=fuzzy) def test_second_sanity(self, fuzzy): dstr = "2014-02-28 22:14:64" with pytest.raises(ParserError): parse(dstr, fuzzy=fuzzy) class TestParseUnimplementedCases: @pytest.mark.xfail def test_somewhat_ambiguous_string(self): # Ref: github issue #487 # The parser is choosing the wrong part for hour # causing datetime to raise an exception. dtstr = '1237 PM BRST Mon Oct 30 2017' res = parse(dtstr, tzinfo=self.tzinfos) assert res == datetime(2017, 10, 30, 12, 37, tzinfo=self.tzinfos) @pytest.mark.xfail def test_YmdH_M_S(self): # found in nasdaq's ftp data dstr = '1991041310:19:24' expected = datetime(1991, 4, 13, 10, 19, 24) res = parse(dstr) assert res == expected, (res, expected) @pytest.mark.xfail def test_first_century(self): dstr = '0031 Nov 03' expected = datetime(31, 11, 3) res = parse(dstr) assert res == expected, res @pytest.mark.xfail def test_era_trailing_year_with_dots(self): dstr = 'A.D.2001' res = parse(dstr) assert res.year == 2001, res @pytest.mark.xfail def test_ad_nospace(self): expected = datetime(6, 5, 19) for dstr in [' 6AD May 19', ' 06AD May 19', ' 006AD May 19', ' 0006AD May 19']: res = parse(dstr) assert res == expected, (dstr, res) @pytest.mark.xfail def test_four_letter_day(self): dstr = 'Frid Dec 30, 2016' expected = datetime(2016, 12, 30) res = parse(dstr) assert res == expected @pytest.mark.xfail def test_non_date_number(self): dstr = '1,700' with pytest.raises(ParserError): parse(dstr) @pytest.mark.xfail def test_on_era(self): # This could be classified as an "eras" test, but the relevant part # about this is the ` on ` dstr = '2:15 PM on January 2nd 1973 A.D.' expected = datetime(1973, 1, 2, 14, 15) res = parse(dstr) assert res == expected @pytest.mark.xfail def test_extraneous_year(self): # This was found in the wild at insidertrading.org dstr = "2011 MARTIN CHILDREN'S IRREVOCABLE TRUST u/a/d NOVEMBER 7, 2012" res = parse(dstr, fuzzy_with_tokens=True) expected = datetime(2012, 11, 7) assert res == expected @pytest.mark.xfail def test_extraneous_year_tokens(self): # This was found in the wild at insidertrading.org # Unlike in the case above, identifying the first "2012" as the year # would not be a problem, but inferring that the latter 2012 is hhmm # is a problem. dstr = "2012 MARTIN CHILDREN'S IRREVOCABLE TRUST u/a/d NOVEMBER 7, 2012" expected = datetime(2012, 11, 7) (res, tokens) = parse(dstr, fuzzy_with_tokens=True) assert res == expected assert tokens == ("2012 MARTIN CHILDREN'S IRREVOCABLE TRUST u/a/d ",) @pytest.mark.xfail def test_extraneous_year2(self): # This was found in the wild at insidertrading.org dstr = ("Berylson Amy Smith 1998 Grantor Retained Annuity Trust " "u/d/t November 2, 1998 f/b/o Jennifer L Berylson") res = parse(dstr, fuzzy_with_tokens=True) expected = datetime(1998, 11, 2) assert res == expected @pytest.mark.xfail def test_extraneous_year3(self): # This was found in the wild at insidertrading.org dstr = "SMITH R & WEISS D 94 CHILD TR FBO M W SMITH UDT 12/1/1994" res = parse(dstr, fuzzy_with_tokens=True) expected = datetime(1994, 12, 1) assert res == expected @pytest.mark.xfail def test_unambiguous_YYYYMM(self): # 171206 can be parsed as YYMMDD. However, 201712 cannot be parsed # as instance of YYMMDD and parser could fallback to YYYYMM format. dstr = "201712" res = parse(dstr) expected = datetime(2017, 12, 1) assert res == expected @pytest.mark.xfail def test_extraneous_numerical_content(self): # ref: https://github.com/dateutil/dateutil/issues/1029 # parser interprets price and percentage as parts of the date dstr = "£14.99 (25% off, until April 20)" res = parse(dstr, fuzzy=True, default=datetime(2000, 1, 1)) expected = datetime(2000, 4, 20) assert res == expected @pytest.mark.skipif(IS_WIN, reason="Windows does not use TZ var") class TestTZVar: def test_parse_unambiguous_nonexistent_local(self): # When dates are specified "EST" even when they should be "EDT" in the # local time zone, we should still assign the local time zone with TZEnvContext('EST+5EDT,M3.2.0/2,M11.1.0/2'): dt_exp = datetime(2011, 8, 1, 12, 30, tzinfo=tz.tzlocal()) dt = parse('2011-08-01T12:30 EST') assert dt.tzname() == 'EDT' assert dt == dt_exp def test_tzlocal_in_gmt(self): # GH #318 with TZEnvContext('GMT0BST,M3.5.0,M10.5.0'): # This is an imaginary datetime in tz.tzlocal() but should still # parse using the GMT-as-alias-for-UTC rule dt = parse('2004-05-01T12:00 GMT') dt_exp = datetime(2004, 5, 1, 12, tzinfo=tz.UTC) assert dt == dt_exp def test_tzlocal_parse_fold(self): # One manifestion of GH #318 with TZEnvContext('EST+5EDT,M3.2.0/2,M11.1.0/2'): dt_exp = datetime(2011, 11, 6, 1, 30, tzinfo=tz.tzlocal()) dt_exp = tz.enfold(dt_exp, fold=1) dt = parse('2011-11-06T01:30 EST') # Because this is ambiguous, until `tz.tzlocal() is tz.tzlocal()` # we'll just check the attributes we care about rather than # dt == dt_exp assert dt.tzname() == dt_exp.tzname() assert dt.replace(tzinfo=None) == dt_exp.replace(tzinfo=None) assert getattr(dt, 'fold') == getattr(dt_exp, 'fold') assert dt.astimezone(tz.UTC) == dt_exp.astimezone(tz.UTC) def test_parse_tzinfos_fold(): NYC = tz.gettz('America/New_York') assert NYC is not None tzinfos = {'EST': NYC, 'EDT': NYC} dt_exp = tz.enfold(datetime(2011, 11, 6, 1, 30, tzinfo=NYC), fold=1) dt = parse('2011-11-06T01:30 EST', tzinfos=tzinfos) assert dt == dt_exp assert dt.tzinfo is dt_exp.tzinfo assert getattr(dt, 'fold') == getattr(dt_exp, 'fold') assert dt.astimezone(tz.UTC) == dt_exp.astimezone(tz.UTC) @pytest.mark.parametrize('dtstr,dt', [ ('5.6h', datetime(2003, 9, 25, 5, 36)), ('5.6m', datetime(2003, 9, 25, 0, 5, 36)), # '5.6s' never had a rounding problem, test added for completeness ('5.6s', datetime(2003, 9, 25, 0, 0, 5, 600000)) ]) def test_rounding_floatlike_strings(dtstr, dt): assert parse(dtstr, default=datetime(2003, 9, 25)) == dt @pytest.mark.parametrize('value', ['1: test', 'Nan']) def test_decimal_error(value): # GH 632, GH 662 - decimal.Decimal raises some non-ParserError exception # when constructed with an invalid value with pytest.raises(ParserError): parse(value) def test_parsererror_repr(): # GH 991 — the __repr__ was not properly indented and so was never defined. # This tests the current behavior of the ParserError __repr__, but the # precise format is not guaranteed to be stable and may change even in # minor versions. This test exists to avoid regressions. s = repr(ParserError("Problem with string: %s", "2019-01-01")) assert s == "ParserError('Problem with string: %s', '2019-01-01')" python_dateutil-4.0.0/tests/test_relativedelta.py0000644000000000000000000007174513615410400017265 0ustar00from ._common import NotAValue import calendar from datetime import datetime, date, timedelta import unittest import pytest from dateutil.relativedelta import relativedelta, MO, TU, WE, FR, SU class RelativeDeltaTest(unittest.TestCase): now = datetime(2003, 9, 17, 20, 54, 47, 282310) today = date(2003, 9, 17) def testInheritance(self): # Ensure that relativedelta is inheritance-friendly. class rdChildClass(relativedelta): pass ccRD = rdChildClass(years=1, months=1, days=1, leapdays=1, weeks=1, hours=1, minutes=1, seconds=1, microseconds=1) rd = relativedelta(years=1, months=1, days=1, leapdays=1, weeks=1, hours=1, minutes=1, seconds=1, microseconds=1) self.assertEqual(type(ccRD + rd), type(ccRD), msg='Addition does not inherit type.') self.assertEqual(type(ccRD - rd), type(ccRD), msg='Subtraction does not inherit type.') self.assertEqual(type(-ccRD), type(ccRD), msg='Negation does not inherit type.') self.assertEqual(type(ccRD * 5.0), type(ccRD), msg='Multiplication does not inherit type.') self.assertEqual(type(ccRD / 5.0), type(ccRD), msg='Division does not inherit type.') def testMonthEndMonthBeginning(self): self.assertEqual(relativedelta(datetime(2003, 1, 31, 23, 59, 59), datetime(2003, 3, 1, 0, 0, 0)), relativedelta(months=-1, seconds=-1)) self.assertEqual(relativedelta(datetime(2003, 3, 1, 0, 0, 0), datetime(2003, 1, 31, 23, 59, 59)), relativedelta(months=1, seconds=1)) def testMonthEndMonthBeginningLeapYear(self): self.assertEqual(relativedelta(datetime(2012, 1, 31, 23, 59, 59), datetime(2012, 3, 1, 0, 0, 0)), relativedelta(months=-1, seconds=-1)) self.assertEqual(relativedelta(datetime(2003, 3, 1, 0, 0, 0), datetime(2003, 1, 31, 23, 59, 59)), relativedelta(months=1, seconds=1)) def testNextMonth(self): self.assertEqual(self.now+relativedelta(months=+1), datetime(2003, 10, 17, 20, 54, 47, 282310)) def testNextMonthPlusOneWeek(self): self.assertEqual(self.now+relativedelta(months=+1, weeks=+1), datetime(2003, 10, 24, 20, 54, 47, 282310)) def testNextMonthPlusOneWeek10am(self): self.assertEqual(self.today + relativedelta(months=+1, weeks=+1, hour=10), datetime(2003, 10, 24, 10, 0)) def testNextMonthPlusOneWeek10amDiff(self): self.assertEqual(relativedelta(datetime(2003, 10, 24, 10, 0), self.today), relativedelta(months=+1, days=+7, hours=+10)) def testOneMonthBeforeOneYear(self): self.assertEqual(self.now+relativedelta(years=+1, months=-1), datetime(2004, 8, 17, 20, 54, 47, 282310)) def testMonthsOfDiffNumOfDays(self): self.assertEqual(date(2003, 1, 27)+relativedelta(months=+1), date(2003, 2, 27)) self.assertEqual(date(2003, 1, 31)+relativedelta(months=+1), date(2003, 2, 28)) self.assertEqual(date(2003, 1, 31)+relativedelta(months=+2), date(2003, 3, 31)) def testMonthsOfDiffNumOfDaysWithYears(self): self.assertEqual(date(2000, 2, 28)+relativedelta(years=+1), date(2001, 2, 28)) self.assertEqual(date(2000, 2, 29)+relativedelta(years=+1), date(2001, 2, 28)) self.assertEqual(date(1999, 2, 28)+relativedelta(years=+1), date(2000, 2, 28)) self.assertEqual(date(1999, 3, 1)+relativedelta(years=+1), date(2000, 3, 1)) self.assertEqual(date(1999, 3, 1)+relativedelta(years=+1), date(2000, 3, 1)) self.assertEqual(date(2001, 2, 28)+relativedelta(years=-1), date(2000, 2, 28)) self.assertEqual(date(2001, 3, 1)+relativedelta(years=-1), date(2000, 3, 1)) def testNextFriday(self): self.assertEqual(self.today+relativedelta(weekday=FR), date(2003, 9, 19)) def testNextFridayInt(self): self.assertEqual(self.today+relativedelta(weekday=calendar.FRIDAY), date(2003, 9, 19)) def testLastFridayInThisMonth(self): self.assertEqual(self.today+relativedelta(day=31, weekday=FR(-1)), date(2003, 9, 26)) def testLastDayOfFebruary(self): self.assertEqual(date(2021, 2, 1) + relativedelta(day=31), date(2021, 2, 28)) def testLastDayOfFebruaryLeapYear(self): self.assertEqual(date(2020, 2, 1) + relativedelta(day=31), date(2020, 2, 29)) def testNextWednesdayIsToday(self): self.assertEqual(self.today+relativedelta(weekday=WE), date(2003, 9, 17)) def testNextWednesdayNotToday(self): self.assertEqual(self.today+relativedelta(days=+1, weekday=WE), date(2003, 9, 24)) def testAddMoreThan12Months(self): self.assertEqual(date(2003, 12, 1) + relativedelta(months=+13), date(2005, 1, 1)) def testAddNegativeMonths(self): self.assertEqual(date(2003, 1, 1) + relativedelta(months=-2), date(2002, 11, 1)) def test15thISOYearWeek(self): self.assertEqual(date(2003, 1, 1) + relativedelta(day=4, weeks=+14, weekday=MO(-1)), date(2003, 4, 7)) def testMillenniumAge(self): self.assertEqual(relativedelta(self.now, date(2001, 1, 1)), relativedelta(years=+2, months=+8, days=+16, hours=+20, minutes=+54, seconds=+47, microseconds=+282310)) def testJohnAge(self): self.assertEqual(relativedelta(self.now, datetime(1978, 4, 5, 12, 0)), relativedelta(years=+25, months=+5, days=+12, hours=+8, minutes=+54, seconds=+47, microseconds=+282310)) def testJohnAgeWithDate(self): self.assertEqual(relativedelta(self.today, datetime(1978, 4, 5, 12, 0)), relativedelta(years=+25, months=+5, days=+11, hours=+12)) def testYearDay(self): self.assertEqual(date(2003, 1, 1)+relativedelta(yearday=260), date(2003, 9, 17)) self.assertEqual(date(2002, 1, 1)+relativedelta(yearday=260), date(2002, 9, 17)) self.assertEqual(date(2000, 1, 1)+relativedelta(yearday=260), date(2000, 9, 16)) self.assertEqual(self.today+relativedelta(yearday=261), date(2003, 9, 18)) def testYearDayBug(self): # Tests a problem reported by Adam Ryan. self.assertEqual(date(2010, 1, 1)+relativedelta(yearday=15), date(2010, 1, 15)) def testNonLeapYearDay(self): self.assertEqual(date(2003, 1, 1)+relativedelta(nlyearday=260), date(2003, 9, 17)) self.assertEqual(date(2002, 1, 1)+relativedelta(nlyearday=260), date(2002, 9, 17)) self.assertEqual(date(2000, 1, 1)+relativedelta(nlyearday=260), date(2000, 9, 17)) self.assertEqual(self.today+relativedelta(yearday=261), date(2003, 9, 18)) def testAddition(self): self.assertEqual(relativedelta(days=10) + relativedelta(years=1, months=2, days=3, hours=4, minutes=5, microseconds=6), relativedelta(years=1, months=2, days=13, hours=4, minutes=5, microseconds=6)) def testAbsoluteAddition(self): self.assertEqual(relativedelta() + relativedelta(day=0, hour=0), relativedelta(day=0, hour=0)) self.assertEqual(relativedelta(day=0, hour=0) + relativedelta(), relativedelta(day=0, hour=0)) def testAdditionToDatetime(self): self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=1), datetime(2000, 1, 2)) def testRightAdditionToDatetime(self): self.assertEqual(relativedelta(days=1) + datetime(2000, 1, 1), datetime(2000, 1, 2)) def testAdditionInvalidType(self): with self.assertRaises(TypeError): relativedelta(days=3) + 9 def testAdditionUnsupportedType(self): # For unsupported types that define their own comparators, etc. self.assertIs(relativedelta(days=1) + NotAValue, NotAValue) def testAdditionFloatValue(self): self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=float(1)), datetime(2000, 1, 2)) self.assertEqual(datetime(2000, 1, 1) + relativedelta(months=float(1)), datetime(2000, 2, 1)) self.assertEqual(datetime(2000, 1, 1) + relativedelta(years=float(1)), datetime(2001, 1, 1)) def testAdditionFloatFractionals(self): self.assertEqual( datetime(2000, 1, 1, 0) + relativedelta(days=0.5), datetime(2000, 1, 1, 12), ) self.assertEqual( datetime(2000, 1, 1, 0, 0) + relativedelta(hours=0.5), datetime(2000, 1, 1, 0, 30), ) self.assertEqual( datetime(2000, 1, 1, 0, 0, 0) + relativedelta(minutes=0.5), datetime(2000, 1, 1, 0, 0, 30), ) self.assertEqual( datetime(2000, 1, 1, 0, 0, 0, 0) + relativedelta(seconds=0.5), datetime(2000, 1, 1, 0, 0, 0, 500000), ) self.assertEqual( datetime(2000, 1, 1, 0, 0, 0, 0) + relativedelta(microseconds=500000.25), datetime(2000, 1, 1, 0, 0, 0, 500000), ) def testSubtraction(self): self.assertEqual(relativedelta(days=10) - relativedelta(years=1, months=2, days=3, hours=4, minutes=5, microseconds=6), relativedelta(years=-1, months=-2, days=7, hours=-4, minutes=-5, microseconds=-6)) def testRightSubtractionFromDatetime(self): self.assertEqual(datetime(2000, 1, 2) - relativedelta(days=1), datetime(2000, 1, 1)) def testSubractionWithDatetime(self): self.assertRaises(TypeError, lambda x, y: x - y, (relativedelta(days=1), datetime(2000, 1, 1))) def testSubtractionInvalidType(self): with self.assertRaises(TypeError): relativedelta(hours=12) - 14 def testSubtractionUnsupportedType(self): self.assertIs(relativedelta(days=1) + NotAValue, NotAValue) def testMultiplication(self): self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=1) * 28, datetime(2000, 1, 29)) self.assertEqual(datetime(2000, 1, 1) + 28 * relativedelta(days=1), datetime(2000, 1, 29)) def testMultiplicationUnsupportedType(self): self.assertIs(relativedelta(days=1) * NotAValue, NotAValue) def testDivision(self): self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=28) / 28, datetime(2000, 1, 2)) def testDivisionUnsupportedType(self): self.assertIs(relativedelta(days=1) / NotAValue, NotAValue) def testBoolean(self): self.assertFalse(relativedelta(days=0)) self.assertTrue(relativedelta(days=1)) def testAbsoluteValueNegative(self): rd_base = relativedelta(years=-1, months=-5, days=-2, hours=-3, minutes=-5, seconds=-2, microseconds=-12) rd_expected = relativedelta(years=1, months=5, days=2, hours=3, minutes=5, seconds=2, microseconds=12) self.assertEqual(abs(rd_base), rd_expected) def testAbsoluteValuePositive(self): rd_base = relativedelta(years=1, months=5, days=2, hours=3, minutes=5, seconds=2, microseconds=12) rd_expected = rd_base self.assertEqual(abs(rd_base), rd_expected) def testComparison(self): d1 = relativedelta(years=1, months=1, days=1, leapdays=0, hours=1, minutes=1, seconds=1, microseconds=1) d2 = relativedelta(years=1, months=1, days=1, leapdays=0, hours=1, minutes=1, seconds=1, microseconds=1) d3 = relativedelta(years=1, months=1, days=1, leapdays=0, hours=1, minutes=1, seconds=1, microseconds=2) self.assertEqual(d1, d2) self.assertNotEqual(d1, d3) def testInequalityTypeMismatch(self): # Different type self.assertFalse(relativedelta(year=1) == 19) self.assertTrue(relativedelta(year=1) != 19) def testInequalityNoneType(self): self.assertFalse(relativedelta(year=1) == None) self.assertTrue(relativedelta(year=1) != None) def testInequalityUnsupportedType(self): self.assertIs(relativedelta(hours=3) == NotAValue, NotAValue) def testInequalityWeekdays(self): # Different weekdays no_wday = relativedelta(year=1997, month=4) wday_mo_1 = relativedelta(year=1997, month=4, weekday=MO(+1)) wday_mo_2 = relativedelta(year=1997, month=4, weekday=MO(+2)) wday_tu = relativedelta(year=1997, month=4, weekday=TU) self.assertTrue(wday_mo_1 == wday_mo_1) self.assertFalse(no_wday == wday_mo_1) self.assertFalse(wday_mo_1 == no_wday) self.assertFalse(wday_mo_1 == wday_mo_2) self.assertFalse(wday_mo_2 == wday_mo_1) self.assertFalse(wday_mo_1 == wday_tu) self.assertFalse(wday_tu == wday_mo_1) def testMonthOverflow(self): self.assertEqual(relativedelta(months=273), relativedelta(years=22, months=9)) def testWeeks(self): # Test that the weeks property is working properly. rd = relativedelta(years=4, months=2, weeks=8, days=6) self.assertEqual((rd.weeks, rd.days), (8, 8 * 7 + 6)) rd.weeks = 3 self.assertEqual((rd.weeks, rd.days), (3, 3 * 7 + 6)) def testRelativeDeltaRepr(self): self.assertEqual(repr(relativedelta(years=1, months=-1, days=15)), 'relativedelta(years=+1, months=-1, days=+15)') self.assertEqual(repr(relativedelta(months=14, seconds=-25)), 'relativedelta(years=+1, months=+2, seconds=-25)') self.assertEqual(repr(relativedelta(month=3, hour=3, weekday=SU(3))), 'relativedelta(month=3, weekday=SU(+3), hour=3)') def testRelativeDeltaFractionalYear(self): with self.assertRaises(ValueError): relativedelta(years=1.5) def testRelativeDeltaFractionalMonth(self): with self.assertRaises(ValueError): relativedelta(months=1.5) def testRelativeDeltaInvalidDatetimeObject(self): with self.assertRaises(TypeError): relativedelta(dt1='2018-01-01', dt2='2018-01-02') with self.assertRaises(TypeError): relativedelta(dt1=datetime(2018, 1, 1), dt2='2018-01-02') with self.assertRaises(TypeError): relativedelta(dt1='2018-01-01', dt2=datetime(2018, 1, 2)) def testRelativeDeltaFractionalAbsolutes(self): # Fractional absolute values will soon be unsupported, # check for the deprecation warning. with pytest.warns(DeprecationWarning): relativedelta(year=2.86) with pytest.warns(DeprecationWarning): relativedelta(month=1.29) with pytest.warns(DeprecationWarning): relativedelta(day=0.44) with pytest.warns(DeprecationWarning): relativedelta(hour=23.98) with pytest.warns(DeprecationWarning): relativedelta(minute=45.21) with pytest.warns(DeprecationWarning): relativedelta(second=13.2) with pytest.warns(DeprecationWarning): relativedelta(microsecond=157221.93) def testRelativeDeltaFractionalRepr(self): rd = relativedelta(years=3, months=-2, days=1.25) self.assertEqual(repr(rd), 'relativedelta(years=+3, months=-2, days=+1.25)') rd = relativedelta(hours=0.5, seconds=9.22) self.assertEqual(repr(rd), 'relativedelta(hours=+0.5, seconds=+9.22)') def testRelativeDeltaFractionalWeeks(self): # Equivalent to days=8, hours=18 rd = relativedelta(weeks=1.25) d1 = datetime(2009, 9, 3, 0, 0) self.assertEqual(d1 + rd, datetime(2009, 9, 11, 18)) def testRelativeDeltaFractionalDays(self): rd1 = relativedelta(days=1.48) d1 = datetime(2009, 9, 3, 0, 0) self.assertEqual(d1 + rd1, datetime(2009, 9, 4, 11, 31, 12)) rd2 = relativedelta(days=1.5) self.assertEqual(d1 + rd2, datetime(2009, 9, 4, 12, 0, 0)) def testRelativeDeltaFractionalHours(self): rd = relativedelta(days=1, hours=12.5) d1 = datetime(2009, 9, 3, 0, 0) self.assertEqual(d1 + rd, datetime(2009, 9, 4, 12, 30, 0)) def testRelativeDeltaFractionalMinutes(self): rd = relativedelta(hours=1, minutes=30.5) d1 = datetime(2009, 9, 3, 0, 0) self.assertEqual(d1 + rd, datetime(2009, 9, 3, 1, 30, 30)) def testRelativeDeltaFractionalSeconds(self): rd = relativedelta(hours=5, minutes=30, seconds=30.5) d1 = datetime(2009, 9, 3, 0, 0) self.assertEqual(d1 + rd, datetime(2009, 9, 3, 5, 30, 30, 500000)) def testRelativeDeltaFractionalPositiveOverflow(self): # Equivalent to (days=1, hours=14) rd1 = relativedelta(days=1.5, hours=2) d1 = datetime(2009, 9, 3, 0, 0) self.assertEqual(d1 + rd1, datetime(2009, 9, 4, 14, 0, 0)) # Equivalent to (days=1, hours=14, minutes=45) rd2 = relativedelta(days=1.5, hours=2.5, minutes=15) d1 = datetime(2009, 9, 3, 0, 0) self.assertEqual(d1 + rd2, datetime(2009, 9, 4, 14, 45)) # Carry back up - equivalent to (days=2, hours=2, minutes=0, seconds=1) rd3 = relativedelta(days=1.5, hours=13, minutes=59.5, seconds=31) self.assertEqual(d1 + rd3, datetime(2009, 9, 5, 2, 0, 1)) def testRelativeDeltaFractionalNegativeDays(self): # Equivalent to (days=-1, hours=-1) rd1 = relativedelta(days=-1.5, hours=11) d1 = datetime(2009, 9, 3, 12, 0) self.assertEqual(d1 + rd1, datetime(2009, 9, 2, 11, 0, 0)) # Equivalent to (days=-1, hours=-9) rd2 = relativedelta(days=-1.25, hours=-3) self.assertEqual(d1 + rd2, datetime(2009, 9, 2, 3)) def testRelativeDeltaNormalizeFractionalDays(self): # Equivalent to (days=2, hours=18) rd1 = relativedelta(days=2.75) self.assertEqual(rd1.normalized(), relativedelta(days=2, hours=18)) # Equivalent to (days=1, hours=11, minutes=31, seconds=12) rd2 = relativedelta(days=1.48) self.assertEqual(rd2.normalized(), relativedelta(days=1, hours=11, minutes=31, seconds=12)) def testRelativeDeltaNormalizeFractionalDays2(self): # Equivalent to (hours=1, minutes=30) rd1 = relativedelta(hours=1.5) self.assertEqual(rd1.normalized(), relativedelta(hours=1, minutes=30)) # Equivalent to (hours=3, minutes=17, seconds=5, microseconds=100) rd2 = relativedelta(hours=3.28472225) self.assertEqual(rd2.normalized(), relativedelta(hours=3, minutes=17, seconds=5, microseconds=100)) def testRelativeDeltaNormalizeFractionalMinutes(self): # Equivalent to (minutes=15, seconds=36) rd1 = relativedelta(minutes=15.6) self.assertEqual(rd1.normalized(), relativedelta(minutes=15, seconds=36)) # Equivalent to (minutes=25, seconds=20, microseconds=25000) rd2 = relativedelta(minutes=25.33375) self.assertEqual(rd2.normalized(), relativedelta(minutes=25, seconds=20, microseconds=25000)) def testRelativeDeltaNormalizeFractionalSeconds(self): # Equivalent to (seconds=45, microseconds=25000) rd1 = relativedelta(seconds=45.025) self.assertEqual(rd1.normalized(), relativedelta(seconds=45, microseconds=25000)) def testRelativeDeltaFractionalPositiveOverflow2(self): # Equivalent to (days=1, hours=14) rd1 = relativedelta(days=1.5, hours=2) self.assertEqual(rd1.normalized(), relativedelta(days=1, hours=14)) # Equivalent to (days=1, hours=14, minutes=45) rd2 = relativedelta(days=1.5, hours=2.5, minutes=15) self.assertEqual(rd2.normalized(), relativedelta(days=1, hours=14, minutes=45)) # Carry back up - equivalent to: # (days=2, hours=2, minutes=0, seconds=2, microseconds=3) rd3 = relativedelta(days=1.5, hours=13, minutes=59.50045, seconds=31.473, microseconds=500003) self.assertEqual(rd3.normalized(), relativedelta(days=2, hours=2, minutes=0, seconds=2, microseconds=3)) def testRelativeDeltaFractionalNegativeOverflow(self): # Equivalent to (days=-1) rd1 = relativedelta(days=-0.5, hours=-12) self.assertEqual(rd1.normalized(), relativedelta(days=-1)) # Equivalent to (days=-1) rd2 = relativedelta(days=-1.5, hours=12) self.assertEqual(rd2.normalized(), relativedelta(days=-1)) # Equivalent to (days=-1, hours=-14, minutes=-45) rd3 = relativedelta(days=-1.5, hours=-2.5, minutes=-15) self.assertEqual(rd3.normalized(), relativedelta(days=-1, hours=-14, minutes=-45)) # Equivalent to (days=-1, hours=-14, minutes=+15) rd4 = relativedelta(days=-1.5, hours=-2.5, minutes=45) self.assertEqual(rd4.normalized(), relativedelta(days=-1, hours=-14, minutes=+15)) # Carry back up - equivalent to: # (days=-2, hours=-2, minutes=0, seconds=-2, microseconds=-3) rd3 = relativedelta(days=-1.5, hours=-13, minutes=-59.50045, seconds=-31.473, microseconds=-500003) self.assertEqual(rd3.normalized(), relativedelta(days=-2, hours=-2, minutes=0, seconds=-2, microseconds=-3)) def testInvalidYearDay(self): with self.assertRaises(ValueError): relativedelta(yearday=367) def testAddTimedeltaToUnpopulatedRelativedelta(self): td = timedelta( days=1, seconds=1, microseconds=1, milliseconds=1, minutes=1, hours=1, weeks=1 ) expected = relativedelta( weeks=1, days=1, hours=1, minutes=1, seconds=1, microseconds=1001 ) self.assertEqual(expected, relativedelta() + td) def testAddTimedeltaToPopulatedRelativeDelta(self): td = timedelta( days=1, seconds=1, microseconds=1, milliseconds=1, minutes=1, hours=1, weeks=1 ) rd = relativedelta( year=1, month=1, day=1, hour=1, minute=1, second=1, microsecond=1, years=1, months=1, days=1, weeks=1, hours=1, minutes=1, seconds=1, microseconds=1 ) expected = relativedelta( year=1, month=1, day=1, hour=1, minute=1, second=1, microsecond=1, years=1, months=1, weeks=2, days=2, hours=2, minutes=2, seconds=2, microseconds=1002, ) self.assertEqual(expected, rd + td) def testHashable(self): try: {relativedelta(minute=1): 'test'} except: self.fail("relativedelta() failed to hash!") def testDayOfMonthPlus(self): assert [ date(2021, 1, 28) + relativedelta(months=1), date(2021, 2, 27) + relativedelta(months=1), date(2021, 4, 29) + relativedelta(months=1), date(2021, 5, 30) + relativedelta(months=1), ] == [ date(2021, 2, 28), date(2021, 3, 27), date(2021, 5, 29), date(2021, 6, 30), ] def testLastDayOfMonthPlus(self): assert [ date(2021, 1, 31) + relativedelta(months=1), date(2021, 1, 30) + relativedelta(months=1), date(2021, 1, 29) + relativedelta(months=1), date(2021, 1, 28) + relativedelta(months=1), date(2021, 2, 28) + relativedelta(months=1), date(2021, 4, 30) + relativedelta(months=1), date(2021, 5, 31) + relativedelta(months=1), ] == [ date(2021, 2, 28), date(2021, 2, 28), date(2021, 2, 28), date(2021, 2, 28), date(2021, 3, 28), date(2021, 5, 30), date(2021, 6, 30), ] def testDayOfMonthMinus(self): assert [ date(2021, 2, 27) - relativedelta(months=1), date(2021, 3, 30) - relativedelta(months=1), date(2021, 3, 29) - relativedelta(months=1), date(2021, 3, 28) - relativedelta(months=1), date(2021, 5, 30) - relativedelta(months=1), date(2021, 6, 29) - relativedelta(months=1), ] == [ date(2021, 1, 27), date(2021, 2, 28), date(2021, 2, 28), date(2021, 2, 28), date(2021, 4, 30), date(2021, 5, 29), ] def testLastDayOfMonthMinus(self): assert [ date(2021, 2, 28) - relativedelta(months=1), date(2021, 3, 31) - relativedelta(months=1), date(2021, 5, 31) - relativedelta(months=1), date(2021, 6, 30) - relativedelta(months=1), ] == [ date(2021, 1, 28), date(2021, 2, 28), date(2021, 4, 30), date(2021, 5, 30), ] @pytest.mark.parametrize("year", [1900, 2000, 2001, 2024]) def test_yearday_is_ordinal_day(year): first = date(year, 1, 1) days = range(1, 366 + calendar.isleap(year)) assert [first + relativedelta(yearday=n) for n in days] == [ first + timedelta(days=n - 1) for n in days ] class RelativeDeltaWeeksPropertyGetterTest(unittest.TestCase): """Test the weeks property getter""" def test_one_day(self): rd = relativedelta(days=1) self.assertEqual(rd.days, 1) self.assertEqual(rd.weeks, 0) def test_minus_one_day(self): rd = relativedelta(days=-1) self.assertEqual(rd.days, -1) self.assertEqual(rd.weeks, 0) def test_height_days(self): rd = relativedelta(days=8) self.assertEqual(rd.days, 8) self.assertEqual(rd.weeks, 1) def test_minus_height_days(self): rd = relativedelta(days=-8) self.assertEqual(rd.days, -8) self.assertEqual(rd.weeks, -1) class RelativeDeltaWeeksPropertySetterTest(unittest.TestCase): """Test the weeks setter which makes a "smart" update of the days attribute""" def test_one_day_set_one_week(self): rd = relativedelta(days=1) rd.weeks = 1 # add 7 days self.assertEqual(rd.days, 8) self.assertEqual(rd.weeks, 1) def test_minus_one_day_set_one_week(self): rd = relativedelta(days=-1) rd.weeks = 1 # add 7 days self.assertEqual(rd.days, 6) self.assertEqual(rd.weeks, 0) def test_height_days_set_minus_one_week(self): rd = relativedelta(days=8) rd.weeks = -1 # change from 1 week, 1 day to -1 week, 1 day self.assertEqual(rd.days, -6) self.assertEqual(rd.weeks, 0) def test_minus_height_days_set_minus_one_week(self): rd = relativedelta(days=-8) rd.weeks = -1 # does not change anything self.assertEqual(rd.days, -8) self.assertEqual(rd.weeks, -1) # vim:ts=4:sw=4:et python_dateutil-4.0.0/tests/test_rrule.py0000644000000000000000000066342313615410400015571 0ustar00import copy import itertools import pickle import threading import unittest from datetime import date, datetime, timedelta from functools import partial import pytest from freezegun import freeze_time from dateutil import tz from dateutil.rrule import ( DAILY, FR, HOURLY, MINUTELY, MO, MONTHLY, SA, SECONDLY, SU, TH, TU, WE, WEEKLY, YEARLY, rrule, rruleset, rrulestr, ) @pytest.mark.rrule class RRuleTest(unittest.TestCase): def _rrulestr_reverse_test(self, rule): """ Call with an `rrule` and it will test that `str(rrule)` generates a string which generates the same `rrule` as the input when passed to `rrulestr()` """ rr_str = str(rule) rrulestr_rrule = rrulestr(rr_str) self.assertEqual(list(rule), list(rrulestr_rrule)) def testStrAppendRRULEToken(self): # `_rrulestr_reverse_test` does not check if the "RRULE:" prefix # property is appended properly, so give it a dedicated test self.assertEqual(str(rrule(YEARLY, count=5, dtstart=datetime(1997, 9, 2, 9, 0))), "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=5") rr_str = ( 'DTSTART:19970105T083000\nRRULE:FREQ=YEARLY;INTERVAL=2' ) self.assertEqual(str(rrulestr(rr_str)), rr_str) def testYearly(self): self.assertEqual(list(rrule(YEARLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testYearlyInterval(self): self.assertEqual(list(rrule(YEARLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0), datetime(2001, 9, 2, 9, 0)]) def testYearlyIntervalLarge(self): self.assertEqual(list(rrule(YEARLY, count=3, interval=100, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(2097, 9, 2, 9, 0), datetime(2197, 9, 2, 9, 0)]) def testYearlyByMonth(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 2, 9, 0), datetime(1998, 3, 2, 9, 0), datetime(1999, 1, 2, 9, 0)]) def testYearlyByMonthDay(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 3, 9, 0), datetime(1997, 10, 1, 9, 0), datetime(1997, 10, 3, 9, 0)]) def testYearlyByMonthAndMonthDay(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 5, 9, 0), datetime(1998, 1, 7, 9, 0), datetime(1998, 3, 5, 9, 0)]) def testYearlyByWeekDay(self): self.assertEqual(list(rrule(YEARLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testYearlyByNWeekDay(self): self.assertEqual(list(rrule(YEARLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 25, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 12, 31, 9, 0)]) def testYearlyByNWeekDayLarge(self): self.assertEqual(list(rrule(YEARLY, count=3, byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 11, 9, 0), datetime(1998, 1, 20, 9, 0), datetime(1998, 12, 17, 9, 0)]) def testYearlyByMonthAndWeekDay(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 8, 9, 0)]) def testYearlyByMonthAndNWeekDay(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 29, 9, 0), datetime(1998, 3, 3, 9, 0)]) def testYearlyByMonthAndNWeekDayLarge(self): # This is interesting because the TH(-3) ends up before # the TU(3). self.assertEqual(list(rrule(YEARLY, count=3, bymonth=(1, 3), byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 15, 9, 0), datetime(1998, 1, 20, 9, 0), datetime(1998, 3, 12, 9, 0)]) def testYearlyByMonthDayAndWeekDay(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 2, 3, 9, 0), datetime(1998, 3, 3, 9, 0)]) def testYearlyByMonthAndMonthDayAndWeekDay(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 3, 3, 9, 0), datetime(2001, 3, 1, 9, 0)]) def testYearlyByYearDay(self): self.assertEqual(list(rrule(YEARLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testYearlyByYearDayNeg(self): self.assertEqual(list(rrule(YEARLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testYearlyByMonthAndYearDay(self): self.assertEqual(list(rrule(YEARLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 4, 10, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testYearlyByMonthAndYearDayNeg(self): self.assertEqual(list(rrule(YEARLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 4, 10, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testYearlyByWeekNo(self): self.assertEqual(list(rrule(YEARLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 5, 11, 9, 0), datetime(1998, 5, 12, 9, 0), datetime(1998, 5, 13, 9, 0)]) def testYearlyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self.assertEqual(list(rrule(YEARLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 29, 9, 0), datetime(1999, 1, 4, 9, 0), datetime(2000, 1, 3, 9, 0)]) def testYearlyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self.assertEqual(list(rrule(YEARLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1998, 12, 27, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testYearlyByWeekNoAndWeekDayLast(self): self.assertEqual(list(rrule(YEARLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1999, 1, 3, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testYearlyByEaster(self): self.assertEqual(list(rrule(YEARLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 12, 9, 0), datetime(1999, 4, 4, 9, 0), datetime(2000, 4, 23, 9, 0)]) def testYearlyByEasterPos(self): self.assertEqual(list(rrule(YEARLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 13, 9, 0), datetime(1999, 4, 5, 9, 0), datetime(2000, 4, 24, 9, 0)]) def testYearlyByEasterNeg(self): self.assertEqual(list(rrule(YEARLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 11, 9, 0), datetime(1999, 4, 3, 9, 0), datetime(2000, 4, 22, 9, 0)]) def testYearlyByWeekNoAndWeekDay53(self): self.assertEqual(list(rrule(YEARLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 12, 28, 9, 0), datetime(2004, 12, 27, 9, 0), datetime(2009, 12, 28, 9, 0)]) def testYearlyByHour(self): self.assertEqual(list(rrule(YEARLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0), datetime(1998, 9, 2, 6, 0), datetime(1998, 9, 2, 18, 0)]) def testYearlyByMinute(self): self.assertEqual(list(rrule(YEARLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6), datetime(1997, 9, 2, 9, 18), datetime(1998, 9, 2, 9, 6)]) def testYearlyBySecond(self): self.assertEqual(list(rrule(YEARLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 6), datetime(1997, 9, 2, 9, 0, 18), datetime(1998, 9, 2, 9, 0, 6)]) def testYearlyByHourAndMinute(self): self.assertEqual(list(rrule(YEARLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6), datetime(1997, 9, 2, 18, 18), datetime(1998, 9, 2, 6, 6)]) def testYearlyByHourAndSecond(self): self.assertEqual(list(rrule(YEARLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 6), datetime(1997, 9, 2, 18, 0, 18), datetime(1998, 9, 2, 6, 0, 6)]) def testYearlyByMinuteAndSecond(self): self.assertEqual(list(rrule(YEARLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 6), datetime(1997, 9, 2, 9, 6, 18), datetime(1997, 9, 2, 9, 18, 6)]) def testYearlyByHourAndMinuteAndSecond(self): self.assertEqual(list(rrule(YEARLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 6), datetime(1997, 9, 2, 18, 6, 18), datetime(1997, 9, 2, 18, 18, 6)]) def testYearlyBySetPos(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonthday=15, byhour=(6, 18), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 11, 15, 18, 0), datetime(1998, 2, 15, 6, 0), datetime(1998, 11, 15, 18, 0)]) def testMonthly(self): self.assertEqual(list(rrule(MONTHLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 10, 2, 9, 0), datetime(1997, 11, 2, 9, 0)]) def testMonthlyInterval(self): self.assertEqual(list(rrule(MONTHLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 11, 2, 9, 0), datetime(1998, 1, 2, 9, 0)]) def testMonthlyIntervalLarge(self): self.assertEqual(list(rrule(MONTHLY, count=3, interval=18, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1999, 3, 2, 9, 0), datetime(2000, 9, 2, 9, 0)]) def testMonthlyByMonth(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 2, 9, 0), datetime(1998, 3, 2, 9, 0), datetime(1999, 1, 2, 9, 0)]) def testMonthlyByMonthDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 3, 9, 0), datetime(1997, 10, 1, 9, 0), datetime(1997, 10, 3, 9, 0)]) def testMonthlyByMonthAndMonthDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 5, 9, 0), datetime(1998, 1, 7, 9, 0), datetime(1998, 3, 5, 9, 0)]) def testMonthlyByWeekDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) # Third Monday of the month self.assertEqual(rrule(MONTHLY, byweekday=(MO(+3)), dtstart=datetime(1997, 9, 1)).between(datetime(1997, 9, 1), datetime(1997, 12, 1)), [datetime(1997, 9, 15, 0, 0), datetime(1997, 10, 20, 0, 0), datetime(1997, 11, 17, 0, 0)]) def testMonthlyByNWeekDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 25, 9, 0), datetime(1997, 10, 7, 9, 0)]) def testMonthlyByNWeekDayLarge(self): self.assertEqual(list(rrule(MONTHLY, count=3, byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 11, 9, 0), datetime(1997, 9, 16, 9, 0), datetime(1997, 10, 16, 9, 0)]) def testMonthlyByMonthAndWeekDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 8, 9, 0)]) def testMonthlyByMonthAndNWeekDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 29, 9, 0), datetime(1998, 3, 3, 9, 0)]) def testMonthlyByMonthAndNWeekDayLarge(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonth=(1, 3), byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 15, 9, 0), datetime(1998, 1, 20, 9, 0), datetime(1998, 3, 12, 9, 0)]) def testMonthlyByMonthDayAndWeekDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 2, 3, 9, 0), datetime(1998, 3, 3, 9, 0)]) def testMonthlyByMonthAndMonthDayAndWeekDay(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 3, 3, 9, 0), datetime(2001, 3, 1, 9, 0)]) def testMonthlyByYearDay(self): self.assertEqual(list(rrule(MONTHLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testMonthlyByYearDayNeg(self): self.assertEqual(list(rrule(MONTHLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testMonthlyByMonthAndYearDay(self): self.assertEqual(list(rrule(MONTHLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 4, 10, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testMonthlyByMonthAndYearDayNeg(self): self.assertEqual(list(rrule(MONTHLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 4, 10, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testMonthlyByWeekNo(self): self.assertEqual(list(rrule(MONTHLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 5, 11, 9, 0), datetime(1998, 5, 12, 9, 0), datetime(1998, 5, 13, 9, 0)]) def testMonthlyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self.assertEqual(list(rrule(MONTHLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 29, 9, 0), datetime(1999, 1, 4, 9, 0), datetime(2000, 1, 3, 9, 0)]) def testMonthlyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self.assertEqual(list(rrule(MONTHLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1998, 12, 27, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testMonthlyByWeekNoAndWeekDayLast(self): self.assertEqual(list(rrule(MONTHLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1999, 1, 3, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testMonthlyByWeekNoAndWeekDay53(self): self.assertEqual(list(rrule(MONTHLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 12, 28, 9, 0), datetime(2004, 12, 27, 9, 0), datetime(2009, 12, 28, 9, 0)]) def testMonthlyByEaster(self): self.assertEqual(list(rrule(MONTHLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 12, 9, 0), datetime(1999, 4, 4, 9, 0), datetime(2000, 4, 23, 9, 0)]) def testMonthlyByEasterPos(self): self.assertEqual(list(rrule(MONTHLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 13, 9, 0), datetime(1999, 4, 5, 9, 0), datetime(2000, 4, 24, 9, 0)]) def testMonthlyByEasterNeg(self): self.assertEqual(list(rrule(MONTHLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 11, 9, 0), datetime(1999, 4, 3, 9, 0), datetime(2000, 4, 22, 9, 0)]) def testMonthlyByHour(self): self.assertEqual(list(rrule(MONTHLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0), datetime(1997, 10, 2, 6, 0), datetime(1997, 10, 2, 18, 0)]) def testMonthlyByMinute(self): self.assertEqual(list(rrule(MONTHLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6), datetime(1997, 9, 2, 9, 18), datetime(1997, 10, 2, 9, 6)]) def testMonthlyBySecond(self): self.assertEqual(list(rrule(MONTHLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 6), datetime(1997, 9, 2, 9, 0, 18), datetime(1997, 10, 2, 9, 0, 6)]) def testMonthlyByHourAndMinute(self): self.assertEqual(list(rrule(MONTHLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6), datetime(1997, 9, 2, 18, 18), datetime(1997, 10, 2, 6, 6)]) def testMonthlyByHourAndSecond(self): self.assertEqual(list(rrule(MONTHLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 6), datetime(1997, 9, 2, 18, 0, 18), datetime(1997, 10, 2, 6, 0, 6)]) def testMonthlyByMinuteAndSecond(self): self.assertEqual(list(rrule(MONTHLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 6), datetime(1997, 9, 2, 9, 6, 18), datetime(1997, 9, 2, 9, 18, 6)]) def testMonthlyByHourAndMinuteAndSecond(self): self.assertEqual(list(rrule(MONTHLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 6), datetime(1997, 9, 2, 18, 6, 18), datetime(1997, 9, 2, 18, 18, 6)]) def testMonthlyBySetPos(self): self.assertEqual(list(rrule(MONTHLY, count=3, bymonthday=(13, 17), byhour=(6, 18), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 13, 18, 0), datetime(1997, 9, 17, 6, 0), datetime(1997, 10, 13, 18, 0)]) def testWeekly(self): self.assertEqual(list(rrule(WEEKLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testWeeklyInterval(self): self.assertEqual(list(rrule(WEEKLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 16, 9, 0), datetime(1997, 9, 30, 9, 0)]) def testWeeklyIntervalLarge(self): self.assertEqual(list(rrule(WEEKLY, count=3, interval=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1998, 1, 20, 9, 0), datetime(1998, 6, 9, 9, 0)]) def testWeeklyByMonth(self): self.assertEqual(list(rrule(WEEKLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 13, 9, 0), datetime(1998, 1, 20, 9, 0)]) def testWeeklyByMonthDay(self): self.assertEqual(list(rrule(WEEKLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 3, 9, 0), datetime(1997, 10, 1, 9, 0), datetime(1997, 10, 3, 9, 0)]) def testWeeklyByMonthAndMonthDay(self): self.assertEqual(list(rrule(WEEKLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 5, 9, 0), datetime(1998, 1, 7, 9, 0), datetime(1998, 3, 5, 9, 0)]) def testWeeklyByWeekDay(self): self.assertEqual(list(rrule(WEEKLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testWeeklyByNWeekDay(self): self.assertEqual(list(rrule(WEEKLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testWeeklyByMonthAndWeekDay(self): # This test is interesting, because it crosses the year # boundary in a weekly period to find day '1' as a # valid recurrence. self.assertEqual(list(rrule(WEEKLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 8, 9, 0)]) def testWeeklyByMonthAndNWeekDay(self): self.assertEqual(list(rrule(WEEKLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 8, 9, 0)]) def testWeeklyByMonthDayAndWeekDay(self): self.assertEqual(list(rrule(WEEKLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 2, 3, 9, 0), datetime(1998, 3, 3, 9, 0)]) def testWeeklyByMonthAndMonthDayAndWeekDay(self): self.assertEqual(list(rrule(WEEKLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 3, 3, 9, 0), datetime(2001, 3, 1, 9, 0)]) def testWeeklyByYearDay(self): self.assertEqual(list(rrule(WEEKLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testWeeklyByYearDayNeg(self): self.assertEqual(list(rrule(WEEKLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testWeeklyByMonthAndYearDay(self): self.assertEqual(list(rrule(WEEKLY, count=4, bymonth=(1, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 1, 1, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testWeeklyByMonthAndYearDayNeg(self): self.assertEqual(list(rrule(WEEKLY, count=4, bymonth=(1, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 1, 1, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testWeeklyByWeekNo(self): self.assertEqual(list(rrule(WEEKLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 5, 11, 9, 0), datetime(1998, 5, 12, 9, 0), datetime(1998, 5, 13, 9, 0)]) def testWeeklyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self.assertEqual(list(rrule(WEEKLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 29, 9, 0), datetime(1999, 1, 4, 9, 0), datetime(2000, 1, 3, 9, 0)]) def testWeeklyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self.assertEqual(list(rrule(WEEKLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1998, 12, 27, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testWeeklyByWeekNoAndWeekDayLast(self): self.assertEqual(list(rrule(WEEKLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1999, 1, 3, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testWeeklyByWeekNoAndWeekDay53(self): self.assertEqual(list(rrule(WEEKLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 12, 28, 9, 0), datetime(2004, 12, 27, 9, 0), datetime(2009, 12, 28, 9, 0)]) def testWeeklyByEaster(self): self.assertEqual(list(rrule(WEEKLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 12, 9, 0), datetime(1999, 4, 4, 9, 0), datetime(2000, 4, 23, 9, 0)]) def testWeeklyByEasterPos(self): self.assertEqual(list(rrule(WEEKLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 13, 9, 0), datetime(1999, 4, 5, 9, 0), datetime(2000, 4, 24, 9, 0)]) def testWeeklyByEasterNeg(self): self.assertEqual(list(rrule(WEEKLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 11, 9, 0), datetime(1999, 4, 3, 9, 0), datetime(2000, 4, 22, 9, 0)]) def testWeeklyByHour(self): self.assertEqual(list(rrule(WEEKLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0), datetime(1997, 9, 9, 6, 0), datetime(1997, 9, 9, 18, 0)]) def testWeeklyByMinute(self): self.assertEqual(list(rrule(WEEKLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6), datetime(1997, 9, 2, 9, 18), datetime(1997, 9, 9, 9, 6)]) def testWeeklyBySecond(self): self.assertEqual(list(rrule(WEEKLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 6), datetime(1997, 9, 2, 9, 0, 18), datetime(1997, 9, 9, 9, 0, 6)]) def testWeeklyByHourAndMinute(self): self.assertEqual(list(rrule(WEEKLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6), datetime(1997, 9, 2, 18, 18), datetime(1997, 9, 9, 6, 6)]) def testWeeklyByHourAndSecond(self): self.assertEqual(list(rrule(WEEKLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 6), datetime(1997, 9, 2, 18, 0, 18), datetime(1997, 9, 9, 6, 0, 6)]) def testWeeklyByMinuteAndSecond(self): self.assertEqual(list(rrule(WEEKLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 6), datetime(1997, 9, 2, 9, 6, 18), datetime(1997, 9, 2, 9, 18, 6)]) def testWeeklyByHourAndMinuteAndSecond(self): self.assertEqual(list(rrule(WEEKLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 6), datetime(1997, 9, 2, 18, 6, 18), datetime(1997, 9, 2, 18, 18, 6)]) def testWeeklyBySetPos(self): self.assertEqual(list(rrule(WEEKLY, count=3, byweekday=(TU, TH), byhour=(6, 18), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0), datetime(1997, 9, 4, 6, 0), datetime(1997, 9, 9, 18, 0)]) def testDaily(self): self.assertEqual(list(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0)]) def testDailyInterval(self): self.assertEqual(list(rrule(DAILY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 6, 9, 0)]) def testDailyIntervalLarge(self): self.assertEqual(list(rrule(DAILY, count=3, interval=92, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 12, 3, 9, 0), datetime(1998, 3, 5, 9, 0)]) def testDailyByMonth(self): self.assertEqual(list(rrule(DAILY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 1, 2, 9, 0), datetime(1998, 1, 3, 9, 0)]) def testDailyByMonthDay(self): self.assertEqual(list(rrule(DAILY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 3, 9, 0), datetime(1997, 10, 1, 9, 0), datetime(1997, 10, 3, 9, 0)]) def testDailyByMonthAndMonthDay(self): self.assertEqual(list(rrule(DAILY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 5, 9, 0), datetime(1998, 1, 7, 9, 0), datetime(1998, 3, 5, 9, 0)]) def testDailyByWeekDay(self): self.assertEqual(list(rrule(DAILY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testDailyByNWeekDay(self): self.assertEqual(list(rrule(DAILY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testDailyByMonthAndWeekDay(self): self.assertEqual(list(rrule(DAILY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 8, 9, 0)]) def testDailyByMonthAndNWeekDay(self): self.assertEqual(list(rrule(DAILY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 1, 8, 9, 0)]) def testDailyByMonthDayAndWeekDay(self): self.assertEqual(list(rrule(DAILY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 2, 3, 9, 0), datetime(1998, 3, 3, 9, 0)]) def testDailyByMonthAndMonthDayAndWeekDay(self): self.assertEqual(list(rrule(DAILY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 3, 3, 9, 0), datetime(2001, 3, 1, 9, 0)]) def testDailyByYearDay(self): self.assertEqual(list(rrule(DAILY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testDailyByYearDayNeg(self): self.assertEqual(list(rrule(DAILY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 9, 0), datetime(1998, 1, 1, 9, 0), datetime(1998, 4, 10, 9, 0), datetime(1998, 7, 19, 9, 0)]) def testDailyByMonthAndYearDay(self): self.assertEqual(list(rrule(DAILY, count=4, bymonth=(1, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 1, 1, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testDailyByMonthAndYearDayNeg(self): self.assertEqual(list(rrule(DAILY, count=4, bymonth=(1, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 9, 0), datetime(1998, 7, 19, 9, 0), datetime(1999, 1, 1, 9, 0), datetime(1999, 7, 19, 9, 0)]) def testDailyByWeekNo(self): self.assertEqual(list(rrule(DAILY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 5, 11, 9, 0), datetime(1998, 5, 12, 9, 0), datetime(1998, 5, 13, 9, 0)]) def testDailyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self.assertEqual(list(rrule(DAILY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 29, 9, 0), datetime(1999, 1, 4, 9, 0), datetime(2000, 1, 3, 9, 0)]) def testDailyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self.assertEqual(list(rrule(DAILY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1998, 12, 27, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testDailyByWeekNoAndWeekDayLast(self): self.assertEqual(list(rrule(DAILY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 9, 0), datetime(1999, 1, 3, 9, 0), datetime(2000, 1, 2, 9, 0)]) def testDailyByWeekNoAndWeekDay53(self): self.assertEqual(list(rrule(DAILY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 12, 28, 9, 0), datetime(2004, 12, 27, 9, 0), datetime(2009, 12, 28, 9, 0)]) def testDailyByEaster(self): self.assertEqual(list(rrule(DAILY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 12, 9, 0), datetime(1999, 4, 4, 9, 0), datetime(2000, 4, 23, 9, 0)]) def testDailyByEasterPos(self): self.assertEqual(list(rrule(DAILY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 13, 9, 0), datetime(1999, 4, 5, 9, 0), datetime(2000, 4, 24, 9, 0)]) def testDailyByEasterNeg(self): self.assertEqual(list(rrule(DAILY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 11, 9, 0), datetime(1999, 4, 3, 9, 0), datetime(2000, 4, 22, 9, 0)]) def testDailyByHour(self): self.assertEqual(list(rrule(DAILY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0), datetime(1997, 9, 3, 6, 0), datetime(1997, 9, 3, 18, 0)]) def testDailyByMinute(self): self.assertEqual(list(rrule(DAILY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6), datetime(1997, 9, 2, 9, 18), datetime(1997, 9, 3, 9, 6)]) def testDailyBySecond(self): self.assertEqual(list(rrule(DAILY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 6), datetime(1997, 9, 2, 9, 0, 18), datetime(1997, 9, 3, 9, 0, 6)]) def testDailyByHourAndMinute(self): self.assertEqual(list(rrule(DAILY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6), datetime(1997, 9, 2, 18, 18), datetime(1997, 9, 3, 6, 6)]) def testDailyByHourAndSecond(self): self.assertEqual(list(rrule(DAILY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 6), datetime(1997, 9, 2, 18, 0, 18), datetime(1997, 9, 3, 6, 0, 6)]) def testDailyByMinuteAndSecond(self): self.assertEqual(list(rrule(DAILY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 6), datetime(1997, 9, 2, 9, 6, 18), datetime(1997, 9, 2, 9, 18, 6)]) def testDailyByHourAndMinuteAndSecond(self): self.assertEqual(list(rrule(DAILY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 6), datetime(1997, 9, 2, 18, 6, 18), datetime(1997, 9, 2, 18, 18, 6)]) def testDailyBySetPos(self): self.assertEqual(list(rrule(DAILY, count=3, byhour=(6, 18), byminute=(15, 45), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 15), datetime(1997, 9, 3, 6, 45), datetime(1997, 9, 3, 18, 15)]) def testHourly(self): self.assertEqual(list(rrule(HOURLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 10, 0), datetime(1997, 9, 2, 11, 0)]) def testHourlyInterval(self): self.assertEqual(list(rrule(HOURLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 11, 0), datetime(1997, 9, 2, 13, 0)]) def testHourlyIntervalLarge(self): self.assertEqual(list(rrule(HOURLY, count=3, interval=769, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 10, 4, 10, 0), datetime(1997, 11, 5, 11, 0)]) def testHourlyByMonth(self): self.assertEqual(list(rrule(HOURLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 1, 0), datetime(1998, 1, 1, 2, 0)]) def testHourlyByMonthDay(self): self.assertEqual(list(rrule(HOURLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 3, 0, 0), datetime(1997, 9, 3, 1, 0), datetime(1997, 9, 3, 2, 0)]) def testHourlyByMonthAndMonthDay(self): self.assertEqual(list(rrule(HOURLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 5, 0, 0), datetime(1998, 1, 5, 1, 0), datetime(1998, 1, 5, 2, 0)]) def testHourlyByWeekDay(self): self.assertEqual(list(rrule(HOURLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 10, 0), datetime(1997, 9, 2, 11, 0)]) def testHourlyByNWeekDay(self): self.assertEqual(list(rrule(HOURLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 10, 0), datetime(1997, 9, 2, 11, 0)]) def testHourlyByMonthAndWeekDay(self): self.assertEqual(list(rrule(HOURLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 1, 0), datetime(1998, 1, 1, 2, 0)]) def testHourlyByMonthAndNWeekDay(self): self.assertEqual(list(rrule(HOURLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 1, 0), datetime(1998, 1, 1, 2, 0)]) def testHourlyByMonthDayAndWeekDay(self): self.assertEqual(list(rrule(HOURLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 1, 0), datetime(1998, 1, 1, 2, 0)]) def testHourlyByMonthAndMonthDayAndWeekDay(self): self.assertEqual(list(rrule(HOURLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 1, 0), datetime(1998, 1, 1, 2, 0)]) def testHourlyByYearDay(self): self.assertEqual(list(rrule(HOURLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 0, 0), datetime(1997, 12, 31, 1, 0), datetime(1997, 12, 31, 2, 0), datetime(1997, 12, 31, 3, 0)]) def testHourlyByYearDayNeg(self): self.assertEqual(list(rrule(HOURLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 0, 0), datetime(1997, 12, 31, 1, 0), datetime(1997, 12, 31, 2, 0), datetime(1997, 12, 31, 3, 0)]) def testHourlyByMonthAndYearDay(self): self.assertEqual(list(rrule(HOURLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 0, 0), datetime(1998, 4, 10, 1, 0), datetime(1998, 4, 10, 2, 0), datetime(1998, 4, 10, 3, 0)]) def testHourlyByMonthAndYearDayNeg(self): self.assertEqual(list(rrule(HOURLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 0, 0), datetime(1998, 4, 10, 1, 0), datetime(1998, 4, 10, 2, 0), datetime(1998, 4, 10, 3, 0)]) def testHourlyByWeekNo(self): self.assertEqual(list(rrule(HOURLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 5, 11, 0, 0), datetime(1998, 5, 11, 1, 0), datetime(1998, 5, 11, 2, 0)]) def testHourlyByWeekNoAndWeekDay(self): self.assertEqual(list(rrule(HOURLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 29, 0, 0), datetime(1997, 12, 29, 1, 0), datetime(1997, 12, 29, 2, 0)]) def testHourlyByWeekNoAndWeekDayLarge(self): self.assertEqual(list(rrule(HOURLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 0, 0), datetime(1997, 12, 28, 1, 0), datetime(1997, 12, 28, 2, 0)]) def testHourlyByWeekNoAndWeekDayLast(self): self.assertEqual(list(rrule(HOURLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 0, 0), datetime(1997, 12, 28, 1, 0), datetime(1997, 12, 28, 2, 0)]) def testHourlyByWeekNoAndWeekDay53(self): self.assertEqual(list(rrule(HOURLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 12, 28, 0, 0), datetime(1998, 12, 28, 1, 0), datetime(1998, 12, 28, 2, 0)]) def testHourlyByEaster(self): self.assertEqual(list(rrule(HOURLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 12, 0, 0), datetime(1998, 4, 12, 1, 0), datetime(1998, 4, 12, 2, 0)]) def testHourlyByEasterPos(self): self.assertEqual(list(rrule(HOURLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 13, 0, 0), datetime(1998, 4, 13, 1, 0), datetime(1998, 4, 13, 2, 0)]) def testHourlyByEasterNeg(self): self.assertEqual(list(rrule(HOURLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 11, 0, 0), datetime(1998, 4, 11, 1, 0), datetime(1998, 4, 11, 2, 0)]) def testHourlyByHour(self): self.assertEqual(list(rrule(HOURLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0), datetime(1997, 9, 3, 6, 0), datetime(1997, 9, 3, 18, 0)]) def testHourlyByMinute(self): self.assertEqual(list(rrule(HOURLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6), datetime(1997, 9, 2, 9, 18), datetime(1997, 9, 2, 10, 6)]) def testHourlyBySecond(self): self.assertEqual(list(rrule(HOURLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 6), datetime(1997, 9, 2, 9, 0, 18), datetime(1997, 9, 2, 10, 0, 6)]) def testHourlyByHourAndMinute(self): self.assertEqual(list(rrule(HOURLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6), datetime(1997, 9, 2, 18, 18), datetime(1997, 9, 3, 6, 6)]) def testHourlyByHourAndSecond(self): self.assertEqual(list(rrule(HOURLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 6), datetime(1997, 9, 2, 18, 0, 18), datetime(1997, 9, 3, 6, 0, 6)]) def testHourlyByMinuteAndSecond(self): self.assertEqual(list(rrule(HOURLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 6), datetime(1997, 9, 2, 9, 6, 18), datetime(1997, 9, 2, 9, 18, 6)]) def testHourlyByHourAndMinuteAndSecond(self): self.assertEqual(list(rrule(HOURLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 6), datetime(1997, 9, 2, 18, 6, 18), datetime(1997, 9, 2, 18, 18, 6)]) def testHourlyBySetPos(self): self.assertEqual(list(rrule(HOURLY, count=3, byminute=(15, 45), bysecond=(15, 45), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 15, 45), datetime(1997, 9, 2, 9, 45, 15), datetime(1997, 9, 2, 10, 15, 45)]) def testMinutely(self): self.assertEqual(list(rrule(MINUTELY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 9, 1), datetime(1997, 9, 2, 9, 2)]) def testMinutelyInterval(self): self.assertEqual(list(rrule(MINUTELY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 9, 2), datetime(1997, 9, 2, 9, 4)]) def testMinutelyIntervalLarge(self): self.assertEqual(list(rrule(MINUTELY, count=3, interval=1501, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 10, 1), datetime(1997, 9, 4, 11, 2)]) def testMinutelyByMonth(self): self.assertEqual(list(rrule(MINUTELY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 0, 1), datetime(1998, 1, 1, 0, 2)]) def testMinutelyByMonthDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 3, 0, 0), datetime(1997, 9, 3, 0, 1), datetime(1997, 9, 3, 0, 2)]) def testMinutelyByMonthAndMonthDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 5, 0, 0), datetime(1998, 1, 5, 0, 1), datetime(1998, 1, 5, 0, 2)]) def testMinutelyByWeekDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 9, 1), datetime(1997, 9, 2, 9, 2)]) def testMinutelyByNWeekDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 2, 9, 1), datetime(1997, 9, 2, 9, 2)]) def testMinutelyByMonthAndWeekDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 0, 1), datetime(1998, 1, 1, 0, 2)]) def testMinutelyByMonthAndNWeekDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 0, 1), datetime(1998, 1, 1, 0, 2)]) def testMinutelyByMonthDayAndWeekDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 0, 1), datetime(1998, 1, 1, 0, 2)]) def testMinutelyByMonthAndMonthDayAndWeekDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0), datetime(1998, 1, 1, 0, 1), datetime(1998, 1, 1, 0, 2)]) def testMinutelyByYearDay(self): self.assertEqual(list(rrule(MINUTELY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 0, 0), datetime(1997, 12, 31, 0, 1), datetime(1997, 12, 31, 0, 2), datetime(1997, 12, 31, 0, 3)]) def testMinutelyByYearDayNeg(self): self.assertEqual(list(rrule(MINUTELY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 0, 0), datetime(1997, 12, 31, 0, 1), datetime(1997, 12, 31, 0, 2), datetime(1997, 12, 31, 0, 3)]) def testMinutelyByMonthAndYearDay(self): self.assertEqual(list(rrule(MINUTELY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 0, 0), datetime(1998, 4, 10, 0, 1), datetime(1998, 4, 10, 0, 2), datetime(1998, 4, 10, 0, 3)]) def testMinutelyByMonthAndYearDayNeg(self): self.assertEqual(list(rrule(MINUTELY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 0, 0), datetime(1998, 4, 10, 0, 1), datetime(1998, 4, 10, 0, 2), datetime(1998, 4, 10, 0, 3)]) def testMinutelyByWeekNo(self): self.assertEqual(list(rrule(MINUTELY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 5, 11, 0, 0), datetime(1998, 5, 11, 0, 1), datetime(1998, 5, 11, 0, 2)]) def testMinutelyByWeekNoAndWeekDay(self): self.assertEqual(list(rrule(MINUTELY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 29, 0, 0), datetime(1997, 12, 29, 0, 1), datetime(1997, 12, 29, 0, 2)]) def testMinutelyByWeekNoAndWeekDayLarge(self): self.assertEqual(list(rrule(MINUTELY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 0, 0), datetime(1997, 12, 28, 0, 1), datetime(1997, 12, 28, 0, 2)]) def testMinutelyByWeekNoAndWeekDayLast(self): self.assertEqual(list(rrule(MINUTELY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 0, 0), datetime(1997, 12, 28, 0, 1), datetime(1997, 12, 28, 0, 2)]) def testMinutelyByWeekNoAndWeekDay53(self): self.assertEqual(list(rrule(MINUTELY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 12, 28, 0, 0), datetime(1998, 12, 28, 0, 1), datetime(1998, 12, 28, 0, 2)]) def testMinutelyByEaster(self): self.assertEqual(list(rrule(MINUTELY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 12, 0, 0), datetime(1998, 4, 12, 0, 1), datetime(1998, 4, 12, 0, 2)]) def testMinutelyByEasterPos(self): self.assertEqual(list(rrule(MINUTELY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 13, 0, 0), datetime(1998, 4, 13, 0, 1), datetime(1998, 4, 13, 0, 2)]) def testMinutelyByEasterNeg(self): self.assertEqual(list(rrule(MINUTELY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 11, 0, 0), datetime(1998, 4, 11, 0, 1), datetime(1998, 4, 11, 0, 2)]) def testMinutelyByHour(self): self.assertEqual(list(rrule(MINUTELY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0), datetime(1997, 9, 2, 18, 1), datetime(1997, 9, 2, 18, 2)]) def testMinutelyByMinute(self): self.assertEqual(list(rrule(MINUTELY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6), datetime(1997, 9, 2, 9, 18), datetime(1997, 9, 2, 10, 6)]) def testMinutelyBySecond(self): self.assertEqual(list(rrule(MINUTELY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 6), datetime(1997, 9, 2, 9, 0, 18), datetime(1997, 9, 2, 9, 1, 6)]) def testMinutelyByHourAndMinute(self): self.assertEqual(list(rrule(MINUTELY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6), datetime(1997, 9, 2, 18, 18), datetime(1997, 9, 3, 6, 6)]) def testMinutelyByHourAndSecond(self): self.assertEqual(list(rrule(MINUTELY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 6), datetime(1997, 9, 2, 18, 0, 18), datetime(1997, 9, 2, 18, 1, 6)]) def testMinutelyByMinuteAndSecond(self): self.assertEqual(list(rrule(MINUTELY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 6), datetime(1997, 9, 2, 9, 6, 18), datetime(1997, 9, 2, 9, 18, 6)]) def testMinutelyByHourAndMinuteAndSecond(self): self.assertEqual(list(rrule(MINUTELY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 6), datetime(1997, 9, 2, 18, 6, 18), datetime(1997, 9, 2, 18, 18, 6)]) def testMinutelyBySetPos(self): self.assertEqual(list(rrule(MINUTELY, count=3, bysecond=(15, 30, 45), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 15), datetime(1997, 9, 2, 9, 0, 45), datetime(1997, 9, 2, 9, 1, 15)]) def testSecondly(self): self.assertEqual(list(rrule(SECONDLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 0), datetime(1997, 9, 2, 9, 0, 1), datetime(1997, 9, 2, 9, 0, 2)]) def testSecondlyInterval(self): self.assertEqual(list(rrule(SECONDLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 0), datetime(1997, 9, 2, 9, 0, 2), datetime(1997, 9, 2, 9, 0, 4)]) def testSecondlyIntervalLarge(self): self.assertEqual(list(rrule(SECONDLY, count=3, interval=90061, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 0), datetime(1997, 9, 3, 10, 1, 1), datetime(1997, 9, 4, 11, 2, 2)]) def testSecondlyByMonth(self): self.assertEqual(list(rrule(SECONDLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0, 0), datetime(1998, 1, 1, 0, 0, 1), datetime(1998, 1, 1, 0, 0, 2)]) def testSecondlyByMonthDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 3, 0, 0, 0), datetime(1997, 9, 3, 0, 0, 1), datetime(1997, 9, 3, 0, 0, 2)]) def testSecondlyByMonthAndMonthDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 5, 0, 0, 0), datetime(1998, 1, 5, 0, 0, 1), datetime(1998, 1, 5, 0, 0, 2)]) def testSecondlyByWeekDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 0), datetime(1997, 9, 2, 9, 0, 1), datetime(1997, 9, 2, 9, 0, 2)]) def testSecondlyByNWeekDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 0), datetime(1997, 9, 2, 9, 0, 1), datetime(1997, 9, 2, 9, 0, 2)]) def testSecondlyByMonthAndWeekDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0, 0), datetime(1998, 1, 1, 0, 0, 1), datetime(1998, 1, 1, 0, 0, 2)]) def testSecondlyByMonthAndNWeekDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0, 0), datetime(1998, 1, 1, 0, 0, 1), datetime(1998, 1, 1, 0, 0, 2)]) def testSecondlyByMonthDayAndWeekDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0, 0), datetime(1998, 1, 1, 0, 0, 1), datetime(1998, 1, 1, 0, 0, 2)]) def testSecondlyByMonthAndMonthDayAndWeekDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 1, 1, 0, 0, 0), datetime(1998, 1, 1, 0, 0, 1), datetime(1998, 1, 1, 0, 0, 2)]) def testSecondlyByYearDay(self): self.assertEqual(list(rrule(SECONDLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 0, 0, 0), datetime(1997, 12, 31, 0, 0, 1), datetime(1997, 12, 31, 0, 0, 2), datetime(1997, 12, 31, 0, 0, 3)]) def testSecondlyByYearDayNeg(self): self.assertEqual(list(rrule(SECONDLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 31, 0, 0, 0), datetime(1997, 12, 31, 0, 0, 1), datetime(1997, 12, 31, 0, 0, 2), datetime(1997, 12, 31, 0, 0, 3)]) def testSecondlyByMonthAndYearDay(self): self.assertEqual(list(rrule(SECONDLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 0, 0, 0), datetime(1998, 4, 10, 0, 0, 1), datetime(1998, 4, 10, 0, 0, 2), datetime(1998, 4, 10, 0, 0, 3)]) def testSecondlyByMonthAndYearDayNeg(self): self.assertEqual(list(rrule(SECONDLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 10, 0, 0, 0), datetime(1998, 4, 10, 0, 0, 1), datetime(1998, 4, 10, 0, 0, 2), datetime(1998, 4, 10, 0, 0, 3)]) def testSecondlyByWeekNo(self): self.assertEqual(list(rrule(SECONDLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 5, 11, 0, 0, 0), datetime(1998, 5, 11, 0, 0, 1), datetime(1998, 5, 11, 0, 0, 2)]) def testSecondlyByWeekNoAndWeekDay(self): self.assertEqual(list(rrule(SECONDLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 29, 0, 0, 0), datetime(1997, 12, 29, 0, 0, 1), datetime(1997, 12, 29, 0, 0, 2)]) def testSecondlyByWeekNoAndWeekDayLarge(self): self.assertEqual(list(rrule(SECONDLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 0, 0, 0), datetime(1997, 12, 28, 0, 0, 1), datetime(1997, 12, 28, 0, 0, 2)]) def testSecondlyByWeekNoAndWeekDayLast(self): self.assertEqual(list(rrule(SECONDLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 12, 28, 0, 0, 0), datetime(1997, 12, 28, 0, 0, 1), datetime(1997, 12, 28, 0, 0, 2)]) def testSecondlyByWeekNoAndWeekDay53(self): self.assertEqual(list(rrule(SECONDLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 12, 28, 0, 0, 0), datetime(1998, 12, 28, 0, 0, 1), datetime(1998, 12, 28, 0, 0, 2)]) def testSecondlyByEaster(self): self.assertEqual(list(rrule(SECONDLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 12, 0, 0, 0), datetime(1998, 4, 12, 0, 0, 1), datetime(1998, 4, 12, 0, 0, 2)]) def testSecondlyByEasterPos(self): self.assertEqual(list(rrule(SECONDLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 13, 0, 0, 0), datetime(1998, 4, 13, 0, 0, 1), datetime(1998, 4, 13, 0, 0, 2)]) def testSecondlyByEasterNeg(self): self.assertEqual(list(rrule(SECONDLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1998, 4, 11, 0, 0, 0), datetime(1998, 4, 11, 0, 0, 1), datetime(1998, 4, 11, 0, 0, 2)]) def testSecondlyByHour(self): self.assertEqual(list(rrule(SECONDLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 0), datetime(1997, 9, 2, 18, 0, 1), datetime(1997, 9, 2, 18, 0, 2)]) def testSecondlyByMinute(self): self.assertEqual(list(rrule(SECONDLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 0), datetime(1997, 9, 2, 9, 6, 1), datetime(1997, 9, 2, 9, 6, 2)]) def testSecondlyBySecond(self): self.assertEqual(list(rrule(SECONDLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0, 6), datetime(1997, 9, 2, 9, 0, 18), datetime(1997, 9, 2, 9, 1, 6)]) def testSecondlyByHourAndMinute(self): self.assertEqual(list(rrule(SECONDLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 0), datetime(1997, 9, 2, 18, 6, 1), datetime(1997, 9, 2, 18, 6, 2)]) def testSecondlyByHourAndSecond(self): self.assertEqual(list(rrule(SECONDLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 0, 6), datetime(1997, 9, 2, 18, 0, 18), datetime(1997, 9, 2, 18, 1, 6)]) def testSecondlyByMinuteAndSecond(self): self.assertEqual(list(rrule(SECONDLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 6, 6), datetime(1997, 9, 2, 9, 6, 18), datetime(1997, 9, 2, 9, 18, 6)]) def testSecondlyByHourAndMinuteAndSecond(self): self.assertEqual(list(rrule(SECONDLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 18, 6, 6), datetime(1997, 9, 2, 18, 6, 18), datetime(1997, 9, 2, 18, 18, 6)]) def testSecondlyByHourAndMinuteAndSecondBug(self): # This explores a bug found by Mathieu Bridon. self.assertEqual(list(rrule(SECONDLY, count=3, bysecond=(0,), byminute=(1,), dtstart=datetime(2010, 3, 22, 12, 1))), [datetime(2010, 3, 22, 12, 1), datetime(2010, 3, 22, 13, 1), datetime(2010, 3, 22, 14, 1)]) def testHourlyBadRRule(self): """ When `byhour` is specified with `freq=HOURLY`, there are certain combinations of `dtstart` and `byhour` which result in an rrule with no valid values. See https://github.com/dateutil/dateutil/issues/4 """ self.assertRaises(ValueError, rrule, HOURLY, **dict(interval=4, byhour=(7, 11, 15, 19), dtstart=datetime(1997, 9, 2, 9, 0))) def testMinutelyBadRRule(self): """ See :func:`testHourlyBadRRule` for details. """ self.assertRaises(ValueError, rrule, MINUTELY, **dict(interval=12, byminute=(10, 11, 25, 39, 50), dtstart=datetime(1997, 9, 2, 9, 0))) def testSecondlyBadRRule(self): """ See :func:`testHourlyBadRRule` for details. """ self.assertRaises(ValueError, rrule, SECONDLY, **dict(interval=10, bysecond=(2, 15, 37, 42, 59), dtstart=datetime(1997, 9, 2, 9, 0))) def testMinutelyBadComboRRule(self): """ Certain values of :param:`interval` in :class:`rrule`, when combined with certain values of :param:`byhour` create rules which apply to no valid dates. The library should detect this case in the iterator and raise a :exception:`ValueError`. """ def make_bad_rrule(): list(rrule(MINUTELY, interval=120, byhour=(10, 12, 14, 16), count=2, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertRaises(ValueError, make_bad_rrule) def testSecondlyBadComboRRule(self): """ See :func:`testMinutelyBadComboRRule' for details. """ def make_bad_minute_rrule(): list(rrule(SECONDLY, interval=360, byminute=(10, 28, 49), count=4, dtstart=datetime(1997, 9, 2, 9, 0))) def make_bad_hour_rrule(): list(rrule(SECONDLY, interval=43200, byhour=(2, 10, 18, 23), count=4, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertRaises(ValueError, make_bad_minute_rrule) self.assertRaises(ValueError, make_bad_hour_rrule) def testBadUntilCountRRule(self): """ See rfc-5545 3.3.10 - This checks for the deprecation warning, and will eventually check for an error. """ with pytest.warns(DeprecationWarning): rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0), count=3, until=datetime(1997, 9, 4, 9, 0)) def testUntilNotMatching(self): self.assertEqual(list(rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0), until=datetime(1997, 9, 5, 8, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0)]) def testUntilMatching(self): self.assertEqual(list(rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0), until=datetime(1997, 9, 4, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0)]) def testUntilSingle(self): self.assertEqual(list(rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0), until=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0)]) def testUntilEmpty(self): self.assertEqual(list(rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0), until=datetime(1997, 9, 1, 9, 0))), []) def testUntilWithDate(self): self.assertEqual(list(rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0), until=date(1997, 9, 5))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0)]) def testWkStIntervalMO(self): self.assertEqual(list(rrule(WEEKLY, count=3, interval=2, byweekday=(TU, SU), wkst=MO, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 7, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testWkStIntervalSU(self): self.assertEqual(list(rrule(WEEKLY, count=3, interval=2, byweekday=(TU, SU), wkst=SU, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 14, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testDTStartIsDate(self): self.assertEqual(list(rrule(DAILY, count=3, dtstart=date(1997, 9, 2))), [datetime(1997, 9, 2, 0, 0), datetime(1997, 9, 3, 0, 0), datetime(1997, 9, 4, 0, 0)]) def testDTStartWithMicroseconds(self): self.assertEqual(list(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0, 0, 500000))), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0)]) def testMaxYear(self): self.assertEqual(list(rrule(YEARLY, count=3, bymonth=2, bymonthday=31, dtstart=datetime(9997, 9, 2, 9, 0, 0))), []) def testGetItem(self): self.assertEqual(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))[0], datetime(1997, 9, 2, 9, 0)) def testGetItemNeg(self): self.assertEqual(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))[-1], datetime(1997, 9, 4, 9, 0)) def testGetItemSlice(self): self.assertEqual(rrule(DAILY, # count=3, dtstart=datetime(1997, 9, 2, 9, 0))[1:2], [datetime(1997, 9, 3, 9, 0)]) def testGetItemSliceEmpty(self): self.assertEqual(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))[:], [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0)]) def testGetItemSliceStep(self): self.assertEqual(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))[::-2], [datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 2, 9, 0)]) def testCount(self): self.assertEqual(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0)).count(), 3) def testCountZero(self): self.assertEqual(rrule(YEARLY, count=0, dtstart=datetime(1997, 9, 2, 9, 0)).count(), 0) def testContains(self): rr = rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0)) self.assertEqual(datetime(1997, 9, 3, 9, 0) in rr, True) def testContainsNot(self): rr = rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0)) self.assertEqual(datetime(1997, 9, 3, 9, 0) not in rr, False) def testBefore(self): self.assertEqual(rrule(DAILY, # count=5 dtstart=datetime(1997, 9, 2, 9, 0)).before(datetime(1997, 9, 5, 9, 0)), datetime(1997, 9, 4, 9, 0)) def testBeforeInc(self): self.assertEqual(rrule(DAILY, #count=5, dtstart=datetime(1997, 9, 2, 9, 0)) .before(datetime(1997, 9, 5, 9, 0), inc=True), datetime(1997, 9, 5, 9, 0)) def testAfter(self): self.assertEqual(rrule(DAILY, #count=5, dtstart=datetime(1997, 9, 2, 9, 0)) .after(datetime(1997, 9, 4, 9, 0)), datetime(1997, 9, 5, 9, 0)) def testAfterInc(self): self.assertEqual(rrule(DAILY, #count=5, dtstart=datetime(1997, 9, 2, 9, 0)) .after(datetime(1997, 9, 4, 9, 0), inc=True), datetime(1997, 9, 4, 9, 0)) def testXAfter(self): self.assertEqual(list(rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0)) .xafter(datetime(1997, 9, 8, 9, 0), count=12)), [datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 10, 9, 0), datetime(1997, 9, 11, 9, 0), datetime(1997, 9, 12, 9, 0), datetime(1997, 9, 13, 9, 0), datetime(1997, 9, 14, 9, 0), datetime(1997, 9, 15, 9, 0), datetime(1997, 9, 16, 9, 0), datetime(1997, 9, 17, 9, 0), datetime(1997, 9, 18, 9, 0), datetime(1997, 9, 19, 9, 0), datetime(1997, 9, 20, 9, 0)]) def testXAfterInc(self): self.assertEqual(list(rrule(DAILY, dtstart=datetime(1997, 9, 2, 9, 0)) .xafter(datetime(1997, 9, 8, 9, 0), count=12, inc=True)), [datetime(1997, 9, 8, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 10, 9, 0), datetime(1997, 9, 11, 9, 0), datetime(1997, 9, 12, 9, 0), datetime(1997, 9, 13, 9, 0), datetime(1997, 9, 14, 9, 0), datetime(1997, 9, 15, 9, 0), datetime(1997, 9, 16, 9, 0), datetime(1997, 9, 17, 9, 0), datetime(1997, 9, 18, 9, 0), datetime(1997, 9, 19, 9, 0)]) def testBetween(self): self.assertEqual(rrule(DAILY, #count=5, dtstart=datetime(1997, 9, 2, 9, 0)) .between(datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 6, 9, 0)), [datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 5, 9, 0)]) def testBetweenInc(self): self.assertEqual(rrule(DAILY, #count=5, dtstart=datetime(1997, 9, 2, 9, 0)) .between(datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 6, 9, 0), inc=True), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 5, 9, 0), datetime(1997, 9, 6, 9, 0)]) def testCachePre(self): rr = rrule(DAILY, count=15, cache=True, dtstart=datetime(1997, 9, 2, 9, 0)) self.assertEqual(list(rr), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 5, 9, 0), datetime(1997, 9, 6, 9, 0), datetime(1997, 9, 7, 9, 0), datetime(1997, 9, 8, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 10, 9, 0), datetime(1997, 9, 11, 9, 0), datetime(1997, 9, 12, 9, 0), datetime(1997, 9, 13, 9, 0), datetime(1997, 9, 14, 9, 0), datetime(1997, 9, 15, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testCachePost(self): rr = rrule(DAILY, count=15, cache=True, dtstart=datetime(1997, 9, 2, 9, 0)) for x in rr: pass self.assertEqual(list(rr), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 5, 9, 0), datetime(1997, 9, 6, 9, 0), datetime(1997, 9, 7, 9, 0), datetime(1997, 9, 8, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 10, 9, 0), datetime(1997, 9, 11, 9, 0), datetime(1997, 9, 12, 9, 0), datetime(1997, 9, 13, 9, 0), datetime(1997, 9, 14, 9, 0), datetime(1997, 9, 15, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testCachePostInternal(self): rr = rrule(DAILY, count=15, cache=True, dtstart=datetime(1997, 9, 2, 9, 0)) for x in rr: pass self.assertEqual(rr._cache, [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 3, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 5, 9, 0), datetime(1997, 9, 6, 9, 0), datetime(1997, 9, 7, 9, 0), datetime(1997, 9, 8, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 10, 9, 0), datetime(1997, 9, 11, 9, 0), datetime(1997, 9, 12, 9, 0), datetime(1997, 9, 13, 9, 0), datetime(1997, 9, 14, 9, 0), datetime(1997, 9, 15, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testCachePreContains(self): rr = rrule(DAILY, count=3, cache=True, dtstart=datetime(1997, 9, 2, 9, 0)) self.assertEqual(datetime(1997, 9, 3, 9, 0) in rr, True) def testCachePostContains(self): rr = rrule(DAILY, count=3, cache=True, dtstart=datetime(1997, 9, 2, 9, 0)) for x in rr: pass self.assertEqual(datetime(1997, 9, 3, 9, 0) in rr, True) def testStr(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=3\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testXNamed(self): self.assertEqual( list( rrulestr( "DTSTART:20240122T124500\n" "RRULE;X-EVOLUTION-ENDDATE=20240205T124500:FREQ=WEEKLY;COUNT=3;BYDAY=MO\n" ) ), [ datetime(2024, 1, 22, 12, 45), datetime(2024, 1, 29, 12, 45), datetime(2024, 2, 5, 12, 45), ], ) def testStrWithTZID(self): NYC = tz.gettz('America/New_York') self.assertIsNotNone(NYC) self.assertEqual(list(rrulestr( "DTSTART;TZID=America/New_York:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=3\n" )), [datetime(1997, 9, 2, 9, 0, tzinfo=NYC), datetime(1998, 9, 2, 9, 0, tzinfo=NYC), datetime(1999, 9, 2, 9, 0, tzinfo=NYC)]) def testStrWithTZIDMapping(self): rrstr = ("DTSTART;TZID=Eastern:19970902T090000\n" + "RRULE:FREQ=YEARLY;COUNT=3") NYC = tz.gettz('America/New_York') self.assertIsNotNone(NYC) rr = rrulestr(rrstr, tzids={'Eastern': NYC}) exp = [datetime(1997, 9, 2, 9, 0, tzinfo=NYC), datetime(1998, 9, 2, 9, 0, tzinfo=NYC), datetime(1999, 9, 2, 9, 0, tzinfo=NYC)] self.assertEqual(list(rr), exp) def testStrWithTZIDCallable(self): rrstr = ('DTSTART;TZID=UTC+04:19970902T090000\n' + 'RRULE:FREQ=YEARLY;COUNT=3') TZ = tz.tzstr('UTC+04') def parse_tzstr(tzstr): if tzstr is None: raise ValueError('Invalid tzstr') return tz.tzstr(tzstr) rr = rrulestr(rrstr, tzids=parse_tzstr) exp = [datetime(1997, 9, 2, 9, 0, tzinfo=TZ), datetime(1998, 9, 2, 9, 0, tzinfo=TZ), datetime(1999, 9, 2, 9, 0, tzinfo=TZ),] self.assertEqual(list(rr), exp) def testStrWithTZIDCallableFailure(self): rrstr = ('DTSTART;TZID=America/New_York:19970902T090000\n' + 'RRULE:FREQ=YEARLY;COUNT=3') class TzInfoError(Exception): pass def tzinfos(tzstr): if tzstr == 'America/New_York': raise TzInfoError('Invalid!') return None with self.assertRaises(TzInfoError): rrulestr(rrstr, tzids=tzinfos) def testStrWithConflictingTZID(self): # RFC 5545 Section 3.3.5, FORM #2: DATE WITH UTC TIME # https://tools.ietf.org/html/rfc5545#section-3.3.5 # The "TZID" property parameter MUST NOT be applied to DATE-TIME with self.assertRaises(ValueError): rrulestr("DTSTART;TZID=America/New_York:19970902T090000Z\n"+ "RRULE:FREQ=YEARLY;COUNT=3\n") def testStrType(self): self.assertEqual(isinstance(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=3\n" ), rrule), True) def testStrForceSetType(self): self.assertEqual(isinstance(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=3\n" , forceset=True), rruleset), True) def testStrSetType(self): self.assertEqual(isinstance(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=2;BYDAY=TU\n" "RRULE:FREQ=YEARLY;COUNT=1;BYDAY=TH\n" ), rruleset), True) def testStrCase(self): self.assertEqual(list(rrulestr( "dtstart:19970902T090000\n" "rrule:freq=yearly;count=3\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testStrSpaces(self): self.assertEqual(list(rrulestr( " DTSTART:19970902T090000 " " RRULE:FREQ=YEARLY;COUNT=3 " )), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testStrSpacesAndLines(self): self.assertEqual(list(rrulestr( " DTSTART:19970902T090000 \n" " \n" " RRULE:FREQ=YEARLY;COUNT=3 \n" )), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testStrNoDTStart(self): self.assertEqual(list(rrulestr( "RRULE:FREQ=YEARLY;COUNT=3\n" , dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testStrValueOnly(self): self.assertEqual(list(rrulestr( "FREQ=YEARLY;COUNT=3\n" , dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testStrUnfold(self): self.assertEqual(list(rrulestr( "FREQ=YEA\n RLY;COUNT=3\n", unfold=True, dtstart=datetime(1997, 9, 2, 9, 0))), [datetime(1997, 9, 2, 9, 0), datetime(1998, 9, 2, 9, 0), datetime(1999, 9, 2, 9, 0)]) def testStrSet(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=2;BYDAY=TU\n" "RRULE:FREQ=YEARLY;COUNT=1;BYDAY=TH\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testStrSetDate(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=1;BYDAY=TU\n" "RDATE:19970904T090000\n" "RDATE:19970909T090000\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testStrSetExRule(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=6;BYDAY=TU,TH\n" "EXRULE:FREQ=YEARLY;COUNT=3;BYDAY=TH\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testStrSetExDate(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=6;BYDAY=TU,TH\n" "EXDATE:19970904T090000\n" "EXDATE:19970911T090000\n" "EXDATE:19970918T090000\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testStrSetExDateMultiple(self): rrstr = ("DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=6;BYDAY=TU,TH\n" "EXDATE:19970904T090000,19970911T090000,19970918T090000\n") rr = rrulestr(rrstr) assert list(rr) == [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)] def testStrSetExDateWithTZID(self): BXL = tz.gettz('Europe/Brussels') self.assertIsNotNone(BXL) rr = rrulestr("DTSTART;TZID=Europe/Brussels:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=6;BYDAY=TU,TH\n" "EXDATE;TZID=Europe/Brussels:19970904T090000\n" "EXDATE;TZID=Europe/Brussels:19970911T090000\n" "EXDATE;TZID=Europe/Brussels:19970918T090000\n") assert list(rr) == [datetime(1997, 9, 2, 9, 0, tzinfo=BXL), datetime(1997, 9, 9, 9, 0, tzinfo=BXL), datetime(1997, 9, 16, 9, 0, tzinfo=BXL)] def testStrSetExDateValueDateTimeNoTZID(self): rrstr = '\n'.join([ "DTSTART:19970902T090000", "RRULE:FREQ=YEARLY;COUNT=4;BYDAY=TU,TH", "EXDATE;VALUE=DATE-TIME:19970902T090000", "EXDATE;VALUE=DATE-TIME:19970909T090000", ]) rr = rrulestr(rrstr) assert list(rr) == [datetime(1997, 9, 4, 9), datetime(1997, 9, 11, 9)] def testStrSetExDateValueMixDateTimeNoTZID(self): rrstr = '\n'.join([ "DTSTART:19970902T090000", "RRULE:FREQ=YEARLY;COUNT=4;BYDAY=TU,TH", "EXDATE;VALUE=DATE-TIME:19970902T090000", "EXDATE:19970909T090000", ]) rr = rrulestr(rrstr) assert list(rr) == [datetime(1997, 9, 4, 9), datetime(1997, 9, 11, 9)] def testStrSetExDateValueDateTimeWithTZID(self): BXL = tz.gettz('Europe/Brussels') self.assertIsNotNone(BXL) rrstr = '\n'.join([ "DTSTART;VALUE=DATE-TIME;TZID=Europe/Brussels:19970902T090000", "RRULE:FREQ=YEARLY;COUNT=4;BYDAY=TU,TH", "EXDATE;VALUE=DATE-TIME;TZID=Europe/Brussels:19970902T090000", "EXDATE;VALUE=DATE-TIME;TZID=Europe/Brussels:19970909T090000", ]) rr = rrulestr(rrstr) assert list(rr) == [datetime(1997, 9, 4, 9, tzinfo=BXL), datetime(1997, 9, 11, 9, tzinfo=BXL)] def testStrSetExDateValueDate(self): rrstr = '\n'.join([ "DTSTART;VALUE=DATE:19970902", "RRULE:FREQ=YEARLY;COUNT=4;BYDAY=TU,TH", "EXDATE;VALUE=DATE:19970902", "EXDATE;VALUE=DATE:19970909", ]) rr = rrulestr(rrstr) assert list(rr) == [datetime(1997, 9, 4), datetime(1997, 9, 11)] def testStrSetDateAndExDate(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RDATE:19970902T090000\n" "RDATE:19970904T090000\n" "RDATE:19970909T090000\n" "RDATE:19970911T090000\n" "RDATE:19970916T090000\n" "RDATE:19970918T090000\n" "EXDATE:19970904T090000\n" "EXDATE:19970911T090000\n" "EXDATE:19970918T090000\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testStrSetDateAndExRule(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RDATE:19970902T090000\n" "RDATE:19970904T090000\n" "RDATE:19970909T090000\n" "RDATE:19970911T090000\n" "RDATE:19970916T090000\n" "RDATE:19970918T090000\n" "EXRULE:FREQ=YEARLY;COUNT=3;BYDAY=TH\n" )), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testStrKeywords(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=3;INTERVAL=3;" "BYMONTH=3;BYWEEKDAY=TH;BYMONTHDAY=3;" "BYHOUR=3;BYMINUTE=3;BYSECOND=3\n" )), [datetime(2033, 3, 3, 3, 3, 3), datetime(2039, 3, 3, 3, 3, 3), datetime(2072, 3, 3, 3, 3, 3)]) def testStrNWeekDay(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=3;BYDAY=1TU,-1TH\n" )), [datetime(1997, 12, 25, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 12, 31, 9, 0)]) def testStrUntil(self): self.assertEqual(list(rrulestr( "DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;" "UNTIL=19990101T000000;BYDAY=1TU,-1TH\n" )), [datetime(1997, 12, 25, 9, 0), datetime(1998, 1, 6, 9, 0), datetime(1998, 12, 31, 9, 0)]) def testStrValueDatetime(self): rr = rrulestr("DTSTART;VALUE=DATE-TIME:19970902T090000\n" "RRULE:FREQ=YEARLY;COUNT=2") self.assertEqual(list(rr), [datetime(1997, 9, 2, 9, 0, 0), datetime(1998, 9, 2, 9, 0, 0)]) def testStrValueDate(self): rr = rrulestr("DTSTART;VALUE=DATE:19970902\n" "RRULE:FREQ=YEARLY;COUNT=2") self.assertEqual(list(rr), [datetime(1997, 9, 2, 0, 0, 0), datetime(1998, 9, 2, 0, 0, 0)]) def testStrMultipleDTStartComma(self): with pytest.raises(ValueError): rr = rrulestr("DTSTART:19970101T000000,19970202T000000\n" "RRULE:FREQ=YEARLY;COUNT=1") def testStrInvalidUntil(self): with self.assertRaises(ValueError): list(rrulestr("DTSTART:19970902T090000\n" "RRULE:FREQ=YEARLY;" "UNTIL=TheCowsComeHome;BYDAY=1TU,-1TH\n")) def testStrUntilMustBeUTC(self): with self.assertRaises(ValueError): list(rrulestr("DTSTART;TZID=America/New_York:19970902T090000\n" "RRULE:FREQ=YEARLY;" "UNTIL=19990101T000000;BYDAY=1TU,-1TH\n")) def testStrUntilWithTZ(self): NYC = tz.gettz('America/New_York') self.assertIsNotNone(NYC) rr = list(rrulestr("DTSTART;TZID=America/New_York:19970101T000000\n" "RRULE:FREQ=YEARLY;" "UNTIL=19990101T000000Z\n")) self.assertEqual(list(rr), [datetime(1997, 1, 1, 0, 0, 0, tzinfo=NYC), datetime(1998, 1, 1, 0, 0, 0, tzinfo=NYC)]) def testStrEmptyByDay(self): with self.assertRaises(ValueError): list(rrulestr("DTSTART:19970902T090000\n" "FREQ=WEEKLY;" "BYDAY=;" # This part is invalid "WKST=SU")) def testStrInvalidByDay(self): with self.assertRaises(ValueError): list(rrulestr("DTSTART:19970902T090000\n" "FREQ=WEEKLY;" "BYDAY=-1OK;" # This part is invalid "WKST=SU")) def testBadBySetPos(self): self.assertRaises(ValueError, rrule, MONTHLY, count=1, bysetpos=0, dtstart=datetime(1997, 9, 2, 9, 0)) def testBadBySetPosMany(self): self.assertRaises(ValueError, rrule, MONTHLY, count=1, bysetpos=(-1, 0, 1), dtstart=datetime(1997, 9, 2, 9, 0)) # Tests to ensure that str(rrule) works def testToStrYearly(self): rule = rrule(YEARLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0)) self._rrulestr_reverse_test(rule) def testToStrYearlyInterval(self): rule = rrule(YEARLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0)) self._rrulestr_reverse_test(rule) def testToStrYearlyByMonth(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthAndMonthDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByWeekDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByNWeekDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByNWeekDayLarge(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthAndWeekDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthAndNWeekDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthAndNWeekDayLarge(self): # This is interesting because the TH(-3) ends up before # the TU(3). self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonth=(1, 3), byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthAndMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByYearDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByYearDayNeg(self): self._rrulestr_reverse_test(rrule(YEARLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthAndYearDay(self): self._rrulestr_reverse_test(rrule(YEARLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMonthAndYearDayNeg(self): self._rrulestr_reverse_test(rrule(YEARLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByWeekNo(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByWeekNoAndWeekDayLast(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByEaster(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByEasterPos(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByEasterNeg(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByWeekNoAndWeekDay53(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByHour(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMinute(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyBySecond(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByHourAndMinute(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByHourAndSecond(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyByHourAndMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrYearlyBySetPos(self): self._rrulestr_reverse_test(rrule(YEARLY, count=3, bymonthday=15, byhour=(6, 18), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthly(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyInterval(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyIntervalLarge(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, interval=18, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonth(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthAndMonthDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByWeekDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) # Third Monday of the month self.assertEqual(rrule(MONTHLY, byweekday=(MO(+3)), dtstart=datetime(1997, 9, 1)).between(datetime(1997, 9, 1), datetime(1997, 12, 1)), [datetime(1997, 9, 15, 0, 0), datetime(1997, 10, 20, 0, 0), datetime(1997, 11, 17, 0, 0)]) def testToStrMonthlyByNWeekDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByNWeekDayLarge(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthAndWeekDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthAndNWeekDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthAndNWeekDayLarge(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonth=(1, 3), byweekday=(TU(3), TH(-3)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthAndMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByYearDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByYearDayNeg(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthAndYearDay(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMonthAndYearDayNeg(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByWeekNo(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByWeekNoAndWeekDayLast(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByWeekNoAndWeekDay53(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByEaster(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByEasterPos(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByEasterNeg(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByHour(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMinute(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyBySecond(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByHourAndMinute(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByHourAndSecond(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyByHourAndMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMonthlyBySetPos(self): self._rrulestr_reverse_test(rrule(MONTHLY, count=3, bymonthday=(13, 17), byhour=(6, 18), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeekly(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyInterval(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyIntervalLarge(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, interval=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonth(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthAndMonthDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByWeekDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByNWeekDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthAndWeekDay(self): # This test is interesting, because it crosses the year # boundary in a weekly period to find day '1' as a # valid recurrence. self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthAndNWeekDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthAndMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByYearDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByYearDayNeg(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthAndYearDay(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=4, bymonth=(1, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMonthAndYearDayNeg(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=4, bymonth=(1, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByWeekNo(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByWeekNoAndWeekDayLast(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByWeekNoAndWeekDay53(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByEaster(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByEasterPos(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByEasterNeg(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByHour(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMinute(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyBySecond(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByHourAndMinute(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByHourAndSecond(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyByHourAndMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrWeeklyBySetPos(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, byweekday=(TU, TH), byhour=(6, 18), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDaily(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyInterval(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyIntervalLarge(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, interval=92, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonth(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthAndMonthDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByWeekDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByNWeekDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthAndWeekDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthAndNWeekDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthAndMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByYearDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByYearDayNeg(self): self._rrulestr_reverse_test(rrule(DAILY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthAndYearDay(self): self._rrulestr_reverse_test(rrule(DAILY, count=4, bymonth=(1, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMonthAndYearDayNeg(self): self._rrulestr_reverse_test(rrule(DAILY, count=4, bymonth=(1, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByWeekNo(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByWeekNoAndWeekDay(self): # That's a nice one. The first days of week number one # may be in the last year. self._rrulestr_reverse_test(rrule(DAILY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByWeekNoAndWeekDayLarge(self): # Another nice test. The last days of week number 52/53 # may be in the next year. self._rrulestr_reverse_test(rrule(DAILY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByWeekNoAndWeekDayLast(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByWeekNoAndWeekDay53(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByEaster(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByEasterPos(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByEasterNeg(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByHour(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMinute(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyBySecond(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByHourAndMinute(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByHourAndSecond(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyByHourAndMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrDailyBySetPos(self): self._rrulestr_reverse_test(rrule(DAILY, count=3, byhour=(6, 18), byminute=(15, 45), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourly(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyInterval(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyIntervalLarge(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, interval=769, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonth(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthAndMonthDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByWeekDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByNWeekDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthAndWeekDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthAndNWeekDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthAndMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByYearDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByYearDayNeg(self): self._rrulestr_reverse_test(rrule(HOURLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthAndYearDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMonthAndYearDayNeg(self): self._rrulestr_reverse_test(rrule(HOURLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByWeekNo(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByWeekNoAndWeekDay(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByWeekNoAndWeekDayLarge(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByWeekNoAndWeekDayLast(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByWeekNoAndWeekDay53(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByEaster(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByEasterPos(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByEasterNeg(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByHour(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMinute(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyBySecond(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByHourAndMinute(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByHourAndSecond(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyByHourAndMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrHourlyBySetPos(self): self._rrulestr_reverse_test(rrule(HOURLY, count=3, byminute=(15, 45), bysecond=(15, 45), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutely(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyInterval(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyIntervalLarge(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, interval=1501, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonth(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthAndMonthDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByWeekDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByNWeekDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthAndWeekDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthAndNWeekDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthAndMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByYearDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByYearDayNeg(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthAndYearDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMonthAndYearDayNeg(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByWeekNo(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByWeekNoAndWeekDay(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByWeekNoAndWeekDayLarge(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByWeekNoAndWeekDayLast(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByWeekNoAndWeekDay53(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByEaster(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByEasterPos(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByEasterNeg(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByHour(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMinute(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyBySecond(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByHourAndMinute(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByHourAndSecond(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyByHourAndMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrMinutelyBySetPos(self): self._rrulestr_reverse_test(rrule(MINUTELY, count=3, bysecond=(15, 30, 45), bysetpos=(3, -3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondly(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyInterval(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, interval=2, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyIntervalLarge(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, interval=90061, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonth(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bymonth=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bymonthday=(1, 3), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthAndMonthDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bymonth=(1, 3), bymonthday=(5, 7), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByWeekDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByNWeekDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthAndWeekDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bymonth=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthAndNWeekDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bymonth=(1, 3), byweekday=(TU(1), TH(-1)), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthAndMonthDayAndWeekDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bymonth=(1, 3), bymonthday=(1, 3), byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByYearDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=4, byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByYearDayNeg(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=4, byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthAndYearDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=4, bymonth=(4, 7), byyearday=(1, 100, 200, 365), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMonthAndYearDayNeg(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=4, bymonth=(4, 7), byyearday=(-365, -266, -166, -1), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByWeekNo(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byweekno=20, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByWeekNoAndWeekDay(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byweekno=1, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByWeekNoAndWeekDayLarge(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byweekno=52, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByWeekNoAndWeekDayLast(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byweekno=-1, byweekday=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByWeekNoAndWeekDay53(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byweekno=53, byweekday=MO, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByEaster(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byeaster=0, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByEasterPos(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byeaster=1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByEasterNeg(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byeaster=-1, dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByHour(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byhour=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMinute(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyBySecond(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByHourAndMinute(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byhour=(6, 18), byminute=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByHourAndSecond(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byhour=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByHourAndMinuteAndSecond(self): self._rrulestr_reverse_test(rrule(SECONDLY, count=3, byhour=(6, 18), byminute=(6, 18), bysecond=(6, 18), dtstart=datetime(1997, 9, 2, 9, 0))) def testToStrSecondlyByHourAndMinuteAndSecondBug(self): # This explores a bug found by Mathieu Bridon. self._rrulestr_reverse_test(rrule(SECONDLY, count=3, bysecond=(0,), byminute=(1,), dtstart=datetime(2010, 3, 22, 12, 1))) def testToStrWithWkSt(self): self._rrulestr_reverse_test(rrule(WEEKLY, count=3, wkst=SU, dtstart=datetime(1997, 9, 2, 9, 0))) def testReplaceIfSet(self): rr = rrule(YEARLY, count=1, bymonthday=5, dtstart=datetime(1997, 1, 1)) newrr = rr.replace(bymonthday=6) self.assertEqual(list(rr), [datetime(1997, 1, 5)]) self.assertEqual(list(newrr), [datetime(1997, 1, 6)]) def testReplaceIfNotSet(self): rr = rrule(YEARLY, count=1, dtstart=datetime(1997, 1, 1)) newrr = rr.replace(bymonthday=6) self.assertEqual(list(rr), [datetime(1997, 1, 1)]) self.assertEqual(list(newrr), [datetime(1997, 1, 6)]) @pytest.mark.rrule @freeze_time(datetime(2018, 3, 6, 5, 36, tzinfo=tz.UTC)) def test_generated_aware_dtstart(): dtstart_exp = datetime(2018, 3, 6, 5, 36, tzinfo=tz.UTC) UNTIL = datetime(2018, 3, 6, 8, 0, tzinfo=tz.UTC) rule_without_dtstart = rrule(freq=HOURLY, until=UNTIL) rule_with_dtstart = rrule(freq=HOURLY, dtstart=dtstart_exp, until=UNTIL) assert list(rule_without_dtstart) == list(rule_with_dtstart) @pytest.mark.rrule @pytest.mark.rrulestr @pytest.mark.xfail(reason="rrulestr loses time zone, gh issue #637") @freeze_time(datetime(2018, 3, 6, 5, 36, tzinfo=tz.UTC)) def test_generated_aware_dtstart_rrulestr(): rrule_without_dtstart = rrule(freq=HOURLY, until=datetime(2018, 3, 6, 8, 0, tzinfo=tz.UTC)) rrule_r = rrulestr(str(rrule_without_dtstart)) assert list(rrule_r) == list(rrule_without_dtstart) @pytest.mark.rruleset class RRuleSetTest(unittest.TestCase): def testSet(self): rrset = rruleset() rrset.rrule(rrule(YEARLY, count=2, byweekday=TU, dtstart=datetime(1997, 9, 2, 9, 0))) rrset.rrule(rrule(YEARLY, count=1, byweekday=TH, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testSetDate(self): rrset = rruleset() rrset.rrule(rrule(YEARLY, count=1, byweekday=TU, dtstart=datetime(1997, 9, 2, 9, 0))) rrset.rdate(datetime(1997, 9, 4, 9)) rrset.rdate(datetime(1997, 9, 9, 9)) self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testSetExRule(self): rrset = rruleset() rrset.rrule(rrule(YEARLY, count=6, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) rrset.exrule(rrule(YEARLY, count=3, byweekday=TH, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testSetExDate(self): rrset = rruleset() rrset.rrule(rrule(YEARLY, count=6, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) rrset.exdate(datetime(1997, 9, 4, 9)) rrset.exdate(datetime(1997, 9, 11, 9)) rrset.exdate(datetime(1997, 9, 18, 9)) self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testSetExDateRevOrder(self): rrset = rruleset() rrset.rrule(rrule(MONTHLY, count=5, bymonthday=10, dtstart=datetime(2004, 1, 1, 9, 0))) rrset.exdate(datetime(2004, 4, 10, 9, 0)) rrset.exdate(datetime(2004, 2, 10, 9, 0)) self.assertEqual(list(rrset), [datetime(2004, 1, 10, 9, 0), datetime(2004, 3, 10, 9, 0), datetime(2004, 5, 10, 9, 0)]) def testSetDateAndExDate(self): rrset = rruleset() rrset.rdate(datetime(1997, 9, 2, 9)) rrset.rdate(datetime(1997, 9, 4, 9)) rrset.rdate(datetime(1997, 9, 9, 9)) rrset.rdate(datetime(1997, 9, 11, 9)) rrset.rdate(datetime(1997, 9, 16, 9)) rrset.rdate(datetime(1997, 9, 18, 9)) rrset.exdate(datetime(1997, 9, 4, 9)) rrset.exdate(datetime(1997, 9, 11, 9)) rrset.exdate(datetime(1997, 9, 18, 9)) self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testSetDateAndExRule(self): rrset = rruleset() rrset.rdate(datetime(1997, 9, 2, 9)) rrset.rdate(datetime(1997, 9, 4, 9)) rrset.rdate(datetime(1997, 9, 9, 9)) rrset.rdate(datetime(1997, 9, 11, 9)) rrset.rdate(datetime(1997, 9, 16, 9)) rrset.rdate(datetime(1997, 9, 18, 9)) rrset.exrule(rrule(YEARLY, count=3, byweekday=TH, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 9, 9, 0), datetime(1997, 9, 16, 9, 0)]) def testSetCount(self): rrset = rruleset() rrset.rrule(rrule(YEARLY, count=6, byweekday=(TU, TH), dtstart=datetime(1997, 9, 2, 9, 0))) rrset.exrule(rrule(YEARLY, count=3, byweekday=TH, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertEqual(rrset.count(), 3) def testSetCachePre(self): rrset = rruleset() rrset.rrule(rrule(YEARLY, count=2, byweekday=TU, dtstart=datetime(1997, 9, 2, 9, 0))) rrset.rrule(rrule(YEARLY, count=1, byweekday=TH, dtstart=datetime(1997, 9, 2, 9, 0))) self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testSetCachePost(self): rrset = rruleset(cache=True) rrset.rrule(rrule(YEARLY, count=2, byweekday=TU, dtstart=datetime(1997, 9, 2, 9, 0))) rrset.rrule(rrule(YEARLY, count=1, byweekday=TH, dtstart=datetime(1997, 9, 2, 9, 0))) for x in rrset: pass self.assertEqual(list(rrset), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testSetCachePostInternal(self): rrset = rruleset(cache=True) rrset.rrule(rrule(YEARLY, count=2, byweekday=TU, dtstart=datetime(1997, 9, 2, 9, 0))) rrset.rrule(rrule(YEARLY, count=1, byweekday=TH, dtstart=datetime(1997, 9, 2, 9, 0))) for x in rrset: pass self.assertEqual(list(rrset._cache), [datetime(1997, 9, 2, 9, 0), datetime(1997, 9, 4, 9, 0), datetime(1997, 9, 9, 9, 0)]) def testSetRRuleCount(self): # Test that the count is updated when an rrule is added rrset = rruleset(cache=False) for cache in (True, False): rrset = rruleset(cache=cache) rrset.rrule(rrule(YEARLY, count=2, byweekday=TH, dtstart=datetime(1983, 4, 1))) rrset.rrule(rrule(WEEKLY, count=4, byweekday=FR, dtstart=datetime(1991, 6, 3))) # Check the length twice - first one sets a cache, second reads it self.assertEqual(rrset.count(), 6) self.assertEqual(rrset.count(), 6) # This should invalidate the cache and force an update rrset.rrule(rrule(MONTHLY, count=3, dtstart=datetime(1994, 1, 3))) self.assertEqual(rrset.count(), 9) self.assertEqual(rrset.count(), 9) def testSetRDateCount(self): # Test that the count is updated when an rdate is added rrset = rruleset(cache=False) for cache in (True, False): rrset = rruleset(cache=cache) rrset.rrule(rrule(YEARLY, count=2, byweekday=TH, dtstart=datetime(1983, 4, 1))) rrset.rrule(rrule(WEEKLY, count=4, byweekday=FR, dtstart=datetime(1991, 6, 3))) # Check the length twice - first one sets a cache, second reads it self.assertEqual(rrset.count(), 6) self.assertEqual(rrset.count(), 6) # This should invalidate the cache and force an update rrset.rdate(datetime(1993, 2, 14)) self.assertEqual(rrset.count(), 7) self.assertEqual(rrset.count(), 7) def testSetExRuleCount(self): # Test that the count is updated when an exrule is added rrset = rruleset(cache=False) for cache in (True, False): rrset = rruleset(cache=cache) rrset.rrule(rrule(YEARLY, count=2, byweekday=TH, dtstart=datetime(1983, 4, 1))) rrset.rrule(rrule(WEEKLY, count=4, byweekday=FR, dtstart=datetime(1991, 6, 3))) # Check the length twice - first one sets a cache, second reads it self.assertEqual(rrset.count(), 6) self.assertEqual(rrset.count(), 6) # This should invalidate the cache and force an update rrset.exrule(rrule(WEEKLY, count=2, interval=2, dtstart=datetime(1991, 6, 14))) self.assertEqual(rrset.count(), 4) self.assertEqual(rrset.count(), 4) def testSetExDateCount(self): # Test that the count is updated when an rdate is added for cache in (True, False): rrset = rruleset(cache=cache) rrset.rrule(rrule(YEARLY, count=2, byweekday=TH, dtstart=datetime(1983, 4, 1))) rrset.rrule(rrule(WEEKLY, count=4, byweekday=FR, dtstart=datetime(1991, 6, 3))) # Check the length twice - first one sets a cache, second reads it self.assertEqual(rrset.count(), 6) self.assertEqual(rrset.count(), 6) # This should invalidate the cache and force an update rrset.exdate(datetime(1991, 6, 28)) self.assertEqual(rrset.count(), 5) self.assertEqual(rrset.count(), 5) class WeekdayTest(unittest.TestCase): def testInvalidNthWeekday(self): with self.assertRaises(ValueError): FR(0) def testWeekdayCallable(self): # Calling a weekday instance generates a new weekday instance with the # value of n changed. from dateutil.rrule import weekday self.assertEqual(MO(1), weekday(0, 1)) # Calling a weekday instance with the identical n returns the original # object FR_3 = weekday(4, 3) self.assertIs(FR_3(3), FR_3) def testWeekdayEquality(self): # Two weekday objects are not equal if they have different values for n self.assertNotEqual(TH, TH(-1)) self.assertNotEqual(SA(3), SA(2)) def testWeekdayEqualitySubclass(self): # Two weekday objects equal if their "weekday" and "n" attributes are # available and the same class BasicWeekday: def __init__(self, weekday): self.weekday = weekday class BasicNWeekday(BasicWeekday): def __init__(self, weekday, n=None): super().__init__(weekday) self.n = n MO_Basic = BasicWeekday(0) self.assertNotEqual(MO, MO_Basic) self.assertNotEqual(MO(1), MO_Basic) TU_BasicN = BasicNWeekday(1) self.assertEqual(TU, TU_BasicN) self.assertNotEqual(TU(3), TU_BasicN) WE_Basic3 = BasicNWeekday(2, 3) self.assertEqual(WE(3), WE_Basic3) self.assertNotEqual(WE(2), WE_Basic3) def testWeekdayReprNoN(self): no_n_reprs = ('MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU') no_n_wdays = (MO, TU, WE, TH, FR, SA, SU) for repstr, wday in zip(no_n_reprs, no_n_wdays): self.assertEqual(repr(wday), repstr) def testWeekdayReprWithN(self): with_n_reprs = ('WE(+1)', 'TH(-2)', 'SU(+3)') with_n_wdays = (WE(1), TH(-2), SU(+3)) for repstr, wday in zip(with_n_reprs, with_n_wdays): self.assertEqual(repr(wday), repstr) class TaggedRule(rrule): __slots__ = ("tag",) def _pickle_roundtrip(value, protocol=pickle.HIGHEST_PROTOCOL): serialized = pickle.dumps(value, protocol) return pickle.loads(serialized) @pytest.fixture(params=["deepcopy"] + list(range(pickle.HIGHEST_PROTOCOL + 1))) def roundtrip(request): if request.param == "deepcopy": return copy.deepcopy return partial(_pickle_roundtrip, protocol=request.param) @pytest.mark.parametrize("kind", ["rule", "set"]) @pytest.mark.parametrize("state", ["disabled", "empty", "partial", "complete"]) def test_rrule_roundtrip(roundtrip, kind, state): start = datetime(2024, 1, 1) expected = [start + timedelta(days=i) for i in range(25)] cache = state != "disabled" original = rrule(DAILY, dtstart=start, count=25, cache=cache) if kind == "set": result = rruleset(cache=cache) result.rrule(original) result.exrule( rrule(DAILY, dtstart=start, interval=3, count=9, cache=cache) ) result.exdate(expected[1]) extra = start + timedelta(days=35) result.rdate(extra) expected = [ value for i, value in enumerate(expected) if i % 3 and i != 1 ] expected.append(extra) original = result iterator = None if state == "partial": iterator = iter(original) assert next(iterator) == expected[0] elif state == "complete": assert list(original) == expected restored = roundtrip(original) assert list(restored) == expected assert restored.count() == len(expected) assert restored.before(expected[-1]) == expected[-2] assert restored.after(expected[0]) == expected[1] assert restored[2:5] == expected[2:5] assert expected[1] in restored if iterator is not None: assert list(iterator) == expected[1:] assert list(original) == expected @pytest.mark.parametrize("state", ["empty", "partial", "complete"]) def test_restored_rruleset_can_invalidate_cache(roundtrip, state): """Changing a restored set must invalidate its populated cache only.""" start = datetime(2024, 1, 1) expected = [start + timedelta(days=i) for i in range(25)] original = rruleset(cache=True) original.rrule(rrule(DAILY, dtstart=start, count=25, cache=True)) if state == "partial": next(iter(original)) elif state == "complete": list(original) restored = roundtrip(original) # Populate the restored cache before changing the set's recurrence dates. assert list(restored) == expected # Both mutators invalidate the cache; the next iteration must reflect them. restored.exdate(expected[0]) extra = datetime(2024, 3, 1) restored.rdate(extra) assert list(restored) == expected[1:] + [extra] assert list(original) == expected @pytest.mark.parametrize("kind", ["rule", "set"]) def test_unbounded_cached_rule_roundtrip(roundtrip, kind): original = rrule(DAILY, dtstart=datetime(2024, 1, 1), cache=True) if kind == "set": result = rruleset(cache=True) result.rrule(original) original = result expected = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(15)] assert list(itertools.islice(original, 12)) == expected[:12] restored = roundtrip(original) assert list(itertools.islice(restored, 15)) == expected @pytest.fixture( params=[copy.deepcopy] + [ partial(_pickle_roundtrip, protocol=p) for p in range(2, pickle.HIGHEST_PROTOCOL + 1) ], ids=["deepcopy"] + ["pickle-{}".format(p) for p in range(2, pickle.HIGHEST_PROTOCOL + 1)], ) def roundtrip_modern(request): # Slotted subclasses and weekday objects require protocol 2 or later. return request.param def test_cached_rule_preserves_options_and_timezone(roundtrip_modern): original = rrule( MONTHLY, dtstart=datetime(2024, 1, 1, tzinfo=tz.UTC), count=4, byweekday=MO(1), byhour=9, cache=True, ) expected = [ datetime(2024, month, day, 9, tzinfo=tz.UTC) for month, day in [(1, 1), (2, 5), (3, 4), (4, 1)] ] next(iter(original)) # Weekday objects already require protocol 2 or later; their legacy # protocol support is independent of the recurrence cache. restored = roundtrip_modern(original) assert list(restored) == expected assert str(restored) == str(original) @pytest.mark.parametrize("cache", [False, True]) def test_rrule_subclass_state_roundtrip(roundtrip_modern, cache): original = TaggedRule( DAILY, dtstart=datetime(2024, 1, 1), count=2, cache=cache ) original.tag = ["slot value"] original.extra = {"attribute": "value"} restored = roundtrip_modern(original) assert type(restored) is TaggedRule assert restored.tag == original.tag assert restored.extra == original.extra restored.tag.append("new value") assert original.tag == ["slot value"] assert list(restored) == list(original) @pytest.mark.parametrize("kind", ["rule", "set"]) def test_completed_empty_cache_roundtrip(roundtrip, kind): if kind == "rule": original = rrule( DAILY, dtstart=datetime(2024, 1, 1), count=0, cache=True ) else: original = rruleset(cache=True) assert list(original) == [] restored = roundtrip(original) assert list(restored) == [] assert restored.count() == 0 @pytest.mark.smoke @pytest.mark.parametrize("kind", ["rule", "set"]) @pytest.mark.parametrize("state", ["disabled", "empty", "partial", "complete"]) def test_roundtrip_cache_setting_smoke(roundtrip, kind, state): """Smoke test: keep caching enabled without copying cached results.""" # TODO: Use a public interface for the cache setting when one is available. cache = state != "disabled" original = rrule(DAILY, dtstart=datetime(2024, 1, 1), count=25, cache=cache) if kind == "set": result = rruleset(cache=cache) result.rrule(original) original = result if state == "partial": next(iter(original)) elif state == "complete": list(original) original_cache = None if not cache else list(original._cache) restored = roundtrip(original) if cache: assert restored._cache == [] assert restored._len is None assert not restored._cache_complete assert restored._cache_lock is not original._cache_lock assert restored._cache_gen is not original._cache_gen else: assert restored._cache is None assert original._cache == original_cache assert list(restored) == list(original) def _list_with_timeout(iterable, timeout=5): # If the cache lock is never released, iterating blocks forever instead # of raising. Iterate in a background thread so the test fails after # ``timeout`` seconds instead of hanging the suite. result = [] thread = threading.Thread( target=result.extend, args=(iterable,), daemon=True ) thread.start() thread.join(timeout) assert not thread.is_alive(), "Iteration did not finish" return result def test_cached_rrule_iterators_started_before_cache_complete(): dtstart = datetime(2024, 1, 1) expected = list(rrule(DAILY, dtstart=dtstart, count=15)) rr = rrule(DAILY, dtstart=dtstart, count=15, cache=True) started = [iter(rr), iter(rr)] for iterator in started: next(iterator) # Exhaust the rule with a new iterator while the two above are still # partway through. assert _list_with_timeout(rr) == expected for iterator in started: assert _list_with_timeout(iterator) == expected[1:] def test_cached_rrule_included_twice_in_rruleset(): dtstart = datetime(2024, 1, 1) expected = list(rrule(DAILY, dtstart=dtstart, count=15)) rr = rrule(DAILY, dtstart=dtstart, count=15, cache=True) rrset = rruleset() rrset.rrule(rr) rrset.rrule(rr) assert _list_with_timeout(rrset) == expected python_dateutil-4.0.0/tests/test_tz.py0000644000000000000000000030567213615410400015074 0ustar00import base64 import copy import gc import os import pickle import sys import tempfile import unittest import warnings import weakref from datetime import datetime from datetime import time as dt_time from datetime import timedelta, tzinfo from functools import partial from io import BytesIO, StringIO from ._common import ( ComparesEqual, PicklableMixin, TZEnvContext, TzSourceMixin, TZWinContext, ) IS_WIN = sys.platform.startswith('win') import pytest from dateutil import tz as tz from dateutil.parser import parse with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) from dateutil import zoneinfo try: import tzdata except ImportError: tzdata = None # The deprecated dateutil.zoneinfo module is a wrapper around tzdata. requires_tzdata = pytest.mark.skipif( tzdata is None, reason="dateutil.zoneinfo requires tzdata" ) # dateutil imports from dateutil.relativedelta import SU, TH, relativedelta try: from dateutil import tzwin except ImportError as e: if IS_WIN: raise e else: pass MISSING_TARBALL = ("This test fails if you don't have the dateutil " "timezone file installed. Please read the README") TZFILE_EST5EDT = b""" VFppZgAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAADrAAAABAAAABCeph5wn7rrYKCGAHCh ms1gomXicKOD6eCkaq5wpTWnYKZTyvCnFYlgqDOs8Kj+peCqE47wqt6H4KvzcPCsvmngrdNS8K6e S+CvszTwsH4t4LGcUXCyZ0pgs3wzcLRHLGC1XBVwticOYLc793C4BvBguRvZcLnm0mC7BPXwu8a0 YLzk1/C9r9DgvsS58L+PsuDApJvwwW+U4MKEffDDT3bgxGRf8MUvWODGTXxwxw864MgtXnDI+Fdg yg1AcMrYOWDLiPBw0iP0cNJg++DTdeTw1EDd4NVVxvDWIL/g1zWo8NgAoeDZFYrw2eCD4Nr+p3Db wGXg3N6JcN2pgmDevmtw34lkYOCeTXDhaUZg4n4vcONJKGDkXhFw5Vcu4OZHLfDnNxDg6CcP8OkW 8uDqBvHw6vbU4Ovm0/Ds1rbg7ca18O6/02Dvr9Jw8J+1YPGPtHDyf5dg82+WcPRfeWD1T3hw9j9b YPcvWnD4KHfg+Q88cPoIWeD6+Fjw++g74PzYOvD9yB3g/rgc8P+n/+AAl/7wAYfh4AJ34PADcP5g BGD9cAVQ4GAGQN9wBzDCYAeNGXAJEKRgCa2U8ArwhmAL4IVwDNmi4A3AZ3AOuYTgD6mD8BCZZuAR iWXwEnlI4BNpR/AUWSrgFUkp8BY5DOAXKQvwGCIpYBkI7fAaAgtgGvIKcBvh7WAc0exwHcHPYB6x znAfobFgIHYA8CGBk2AiVeLwI2qv4CQ1xPAlSpHgJhWm8Ccqc+An/sNwKQpV4CnepXAq6jfgK76H cCzTVGAtnmlwLrM2YC9+S3AwkxhgMWdn8DJy+mAzR0nwNFLcYDUnK/A2Mr5gNwcN8Dgb2uA45u/w Ofu84DrG0fA7257gPK/ucD27gOA+j9BwP5ti4EBvsnBBhH9gQk+UcENkYWBEL3ZwRURDYEYPWHBH JCVgR/h08EkEB2BJ2FbwSuPpYEu4OPBMzQXgTZga8E6s5+BPd/zwUIzJ4FFhGXBSbKvgU0D7cFRM jeBVIN1wVixv4FcAv3BYFYxgWOChcFn1bmBawINwW9VQYFypn/BdtTJgXomB8F+VFGBgaWPwYX4w 4GJJRfBjXhLgZCkn8GU99OBmEkRwZx3W4GfyJnBo/bjgadIIcGrdmuBrsepwbMa3YG2RzHBupplg b3GucHCGe2BxWsrwcmZdYHM6rPB0Rj9gdRqO8HYvW+B2+nDweA894HjaUvB57x/gero08HvPAeB8 o1Fwfa7j4H6DM3B/jsXgAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAB AAEAAQABAgMBAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAB AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEA AQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAB AAEAAQABAAEAAQABAAEAAQABAAEAAf//x8ABAP//ubAABP//x8ABCP//x8ABDEVEVABFU1QARVdU AEVQVAAAAAABAAAAAQ== """ EUROPE_HELSINKI = b""" VFppZgAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABQAAAAAAAAB1AAAABQAAAA2kc28Yy85RYMy/hdAV I+uQFhPckBcDzZAX876QGOOvkBnToJAaw5GQG7y9EBysrhAdnJ8QHoyQEB98gRAgbHIQIVxjECJM VBAjPEUQJCw2ECUcJxAmDBgQJwVDkCf1NJAo5SWQKdUWkCrFB5ArtPiQLKTpkC2U2pAuhMuQL3S8 kDBkrZAxXdkQMnK0EDM9uxA0UpYQNR2dEDYyeBA2/X8QOBuUkDjdYRA5+3aQOr1DEDvbWJA8pl+Q Pbs6kD6GQZA/mxyQQGYjkEGEORBCRgWQQ2QbEEQl55BFQ/0QRgXJkEcj3xBH7uYQSQPBEEnOyBBK 46MQS66qEEzMv5BNjowQTqyhkE9ubhBQjIOQUVeKkFJsZZBTN2yQVExHkFUXTpBWLCmQVvcwkFgV RhBY1xKQWfUoEFq29JBb1QoQXKAREF207BBef/MQX5TOEGBf1RBhfeqQYj+3EGNdzJBkH5kQZT2u kGYItZBnHZCQZ+iXkGj9cpBpyHmQat1UkGuoW5BsxnEQbYg9kG6mUxBvaB+QcIY1EHFRPBByZhcQ czEeEHRF+RB1EQAQdi8VkHbw4hB4DveQeNDEEHnu2ZB6sKYQe867kHyZwpB9rp2QfnmkkH+Of5AC AQIDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQD BAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAMEAwQDBAME AwQAABdoAAAAACowAQQAABwgAAkAACowAQQAABwgAAlITVQARUVTVABFRVQAAAAAAQEAAAABAQ== """ NEW_YORK = b""" VFppZgAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABAAAABcAAADrAAAABAAAABCeph5wn7rrYKCGAHCh ms1gomXicKOD6eCkaq5wpTWnYKZTyvCnFYlgqDOs8Kj+peCqE47wqt6H4KvzcPCsvmngrdNS8K6e S+CvszTwsH4t4LGcUXCyZ0pgs3wzcLRHLGC1XBVwticOYLc793C4BvBguRvZcLnm0mC7BPXwu8a0 YLzk1/C9r9DgvsS58L+PsuDApJvwwW+U4MKEffDDT3bgxGRf8MUvWODGTXxwxw864MgtXnDI+Fdg yg1AcMrYOWDLiPBw0iP0cNJg++DTdeTw1EDd4NVVxvDWIL/g1zWo8NgAoeDZFYrw2eCD4Nr+p3Db wGXg3N6JcN2pgmDevmtw34lkYOCeTXDhaUZg4n4vcONJKGDkXhFw5Vcu4OZHLfDnNxDg6CcP8OkW 8uDqBvHw6vbU4Ovm0/Ds1rbg7ca18O6/02Dvr9Jw8J+1YPGPtHDyf5dg82+WcPRfeWD1T3hw9j9b YPcvWnD4KHfg+Q88cPoIWeD6+Fjw++g74PzYOvD9yB3g/rgc8P+n/+AAl/7wAYfh4AJ34PADcP5g BGD9cAVQ4GEGQN9yBzDCYgeNGXMJEKRjCa2U9ArwhmQL4IV1DNmi5Q3AZ3YOuYTmD6mD9xCZZucR iWX4EnlI6BNpR/kUWSrpFUkp+RY5DOoXKQv6GCIpaxkI7fsaAgtsGvIKfBvh7Wwc0ex8HcHPbR6x zn0fobFtIHYA/SGBk20iVeL+I2qv7iQ1xP4lSpHuJhWm/ycqc+8n/sOAKQpV8CnepYAq6jfxK76H gSzTVHItnmmCLrM2cy9+S4MwkxhzMWdoBDJy+nQzR0oENFLcdTUnLAU2Mr51NwcOBjgb2vY45vAG Ofu89jrG0gY72572PK/uhj27gPY+j9CGP5ti9kBvsoZBhH92Qk+UhkNkYXZEL3aHRURDd0XzqQdH LV/3R9OLB0kNQfdJs20HSu0j90uciYdM1kB3TXxrh062IndPXE2HUJYEd1E8L4dSdeZ3UxwRh1RV yHdU+/OHVjWqd1blEAdYHsb3WMTyB1n+qPdapNQHW96K91yEtgddvmz3XmSYB1+eTvdgTbSHYYdr d2ItlodjZ013ZA14h2VHL3dl7VqHZycRd2fNPIdpBvN3aa0eh2rm1XdrljsHbM/x9212HQdur9P3 b1X/B3CPtfdxNeEHcm+X93MVwwd0T3n3dP7fh3Y4lnd23sGHeBh4d3i+o4d5+Fp3ep6Fh3vYPHd8 fmeHfbged35eSYd/mAB3AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAB AAEAAQABAgMBAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAB AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEA AQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAB AAEAAQABAAEAAQABAAEAAQABAAEAAf//x8ABAP//ubAABP//x8ABCP//x8ABDEVEVABFU1QARVdU AEVQVAAEslgAAAAAAQWk7AEAAAACB4YfggAAAAMJZ1MDAAAABAtIhoQAAAAFDSsLhQAAAAYPDD8G AAAABxDtcocAAAAIEs6mCAAAAAkVn8qJAAAACheA/goAAAALGWIxiwAAAAwdJeoMAAAADSHa5Q0A AAAOJZ6djgAAAA8nf9EPAAAAECpQ9ZAAAAARLDIpEQAAABIuE1ySAAAAEzDnJBMAAAAUM7hIlAAA ABU2jBAVAAAAFkO3G5YAAAAXAAAAAQAAAAE= """ TZICAL_EST5EDT = """ BEGIN:VTIMEZONE TZID:US-Eastern LAST-MODIFIED:19870101T000000Z TZURL:http://zones.stds_r_us.net/tz/US-Eastern BEGIN:STANDARD DTSTART:19671029T020000 RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 TZNAME:EST END:STANDARD BEGIN:DAYLIGHT DTSTART:19870405T020000 RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 TZNAME:EDT END:DAYLIGHT END:VTIMEZONE """ TZICAL_PST8PDT = """ BEGIN:VTIMEZONE TZID:US-Pacific LAST-MODIFIED:19870101T000000Z BEGIN:STANDARD DTSTART:19671029T020000 RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 TZOFFSETFROM:-0700 TZOFFSETTO:-0800 TZNAME:PST END:STANDARD BEGIN:DAYLIGHT DTSTART:19870405T020000 RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 TZOFFSETFROM:-0800 TZOFFSETTO:-0700 TZNAME:PDT END:DAYLIGHT END:VTIMEZONE """ EST_TUPLE = ('EST', timedelta(hours=-5), timedelta(hours=0)) EDT_TUPLE = ('EDT', timedelta(hours=-4), timedelta(hours=1)) ### # Helper functions def get_timezone_tuple(dt): """Retrieve a (tzname, utcoffset, dst) tuple for a given DST""" return dt.tzname(), dt.utcoffset(), dt.dst() ### # Mix-ins class context_passthrough: def __init__(*args, **kwargs): pass def __enter__(*args, **kwargs): pass def __exit__(*args, **kwargs): pass class TzFoldMixin: """ Mix-in class for testing ambiguous times """ def gettz(self, tzname): raise NotImplementedError def _get_tzname(self, tzname): return tzname def _gettz_context(self, tzname): return context_passthrough() def testFoldPositiveUTCOffset(self): # Test that we can resolve ambiguous times tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD = self.gettz(tzname) t0_u = datetime(2012, 3, 31, 15, 30, tzinfo=tz.UTC) # AEST t1_u = datetime(2012, 3, 31, 16, 30, tzinfo=tz.UTC) # AEDT t0_syd0 = t0_u.astimezone(SYD) t1_syd1 = t1_u.astimezone(SYD) self.assertEqual(t0_syd0.replace(tzinfo=None), datetime(2012, 4, 1, 2, 30)) self.assertEqual(t1_syd1.replace(tzinfo=None), datetime(2012, 4, 1, 2, 30)) self.assertEqual(t0_syd0.utcoffset(), timedelta(hours=11)) self.assertEqual(t1_syd1.utcoffset(), timedelta(hours=10)) def testGapPositiveUTCOffset(self): # Test that we don't have a problem around gaps. tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD = self.gettz(tzname) t0_u = datetime(2012, 10, 6, 15, 30, tzinfo=tz.UTC) # AEST t1_u = datetime(2012, 10, 6, 16, 30, tzinfo=tz.UTC) # AEDT t0 = t0_u.astimezone(SYD) t1 = t1_u.astimezone(SYD) self.assertEqual(t0.replace(tzinfo=None), datetime(2012, 10, 7, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2012, 10, 7, 3, 30)) self.assertEqual(t0.utcoffset(), timedelta(hours=10)) self.assertEqual(t1.utcoffset(), timedelta(hours=11)) def testFoldNegativeUTCOffset(self): # Test that we can resolve ambiguous times tzname = self._get_tzname('America/Toronto') with self._gettz_context(tzname): TOR = self.gettz(tzname) t0_u = datetime(2011, 11, 6, 5, 30, tzinfo=tz.UTC) t1_u = datetime(2011, 11, 6, 6, 30, tzinfo=tz.UTC) t0_tor = t0_u.astimezone(TOR) t1_tor = t1_u.astimezone(TOR) self.assertEqual(t0_tor.replace(tzinfo=None), datetime(2011, 11, 6, 1, 30)) self.assertEqual(t1_tor.replace(tzinfo=None), datetime(2011, 11, 6, 1, 30)) self.assertNotEqual(t0_tor.tzname(), t1_tor.tzname()) self.assertEqual(t0_tor.utcoffset(), timedelta(hours=-4.0)) self.assertEqual(t1_tor.utcoffset(), timedelta(hours=-5.0)) def testGapNegativeUTCOffset(self): # Test that we don't have a problem around gaps. tzname = self._get_tzname('America/Toronto') with self._gettz_context(tzname): TOR = self.gettz(tzname) t0_u = datetime(2011, 3, 13, 6, 30, tzinfo=tz.UTC) t1_u = datetime(2011, 3, 13, 7, 30, tzinfo=tz.UTC) t0 = t0_u.astimezone(TOR) t1 = t1_u.astimezone(TOR) self.assertEqual(t0.replace(tzinfo=None), datetime(2011, 3, 13, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2011, 3, 13, 3, 30)) self.assertNotEqual(t0, t1) self.assertEqual(t0.utcoffset(), timedelta(hours=-5.0)) self.assertEqual(t1.utcoffset(), timedelta(hours=-4.0)) def testFoldLondon(self): tzname = self._get_tzname('Europe/London') with self._gettz_context(tzname): LON = self.gettz(tzname) UTC = tz.UTC t0_u = datetime(2013, 10, 27, 0, 30, tzinfo=UTC) # BST t1_u = datetime(2013, 10, 27, 1, 30, tzinfo=UTC) # GMT t0 = t0_u.astimezone(LON) t1 = t1_u.astimezone(LON) self.assertEqual(t0.replace(tzinfo=None), datetime(2013, 10, 27, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2013, 10, 27, 1, 30)) self.assertEqual(t0.utcoffset(), timedelta(hours=1)) self.assertEqual(t1.utcoffset(), timedelta(hours=0)) def testFoldIndependence(self): tzname = self._get_tzname('America/New_York') with self._gettz_context(tzname): NYC = self.gettz(tzname) UTC = tz.UTC hour = timedelta(hours=1) # Firmly 2015-11-01 0:30 EDT-4 pre_dst = datetime(2015, 11, 1, 0, 30, tzinfo=NYC) # Ambiguous between 2015-11-01 1:30 EDT-4 and 2015-11-01 1:30 EST-5 in_dst = pre_dst + hour in_dst_tzname_0 = in_dst.tzname() # Stash the tzname - EDT # Doing the arithmetic in UTC creates a date that is unambiguously # 2015-11-01 1:30 EDT-5 in_dst_via_utc = (pre_dst.astimezone(UTC) + 2*hour).astimezone(NYC) # Make sure the dates are actually ambiguous self.assertEqual(in_dst, in_dst_via_utc) # Make sure we got the right folding behavior self.assertNotEqual(in_dst_via_utc.tzname(), in_dst_tzname_0) # Now check to make sure in_dst's tzname hasn't changed self.assertEqual(in_dst_tzname_0, in_dst.tzname()) def testInZoneFoldEquality(self): # Two datetimes in the same zone are considered to be equal if their # wall times are equal, even if they have different absolute times. tzname = self._get_tzname('America/New_York') with self._gettz_context(tzname): NYC = self.gettz(tzname) UTC = tz.UTC dt0 = datetime(2011, 11, 6, 1, 30, tzinfo=NYC) dt1 = tz.enfold(dt0, fold=1) # Make sure these actually represent different times self.assertNotEqual(dt0.astimezone(UTC), dt1.astimezone(UTC)) # Test that they compare equal self.assertEqual(dt0, dt1) def _test_ambiguous_time(self, dt, tzid, ambiguous): # This is a test to check that the individual is_ambiguous values # on the _tzinfo subclasses work. tzname = self._get_tzname(tzid) with self._gettz_context(tzname): tzi = self.gettz(tzname) self.assertEqual(tz.datetime_ambiguous(dt, tz=tzi), ambiguous) def testAmbiguousNegativeUTCOffset(self): self._test_ambiguous_time(datetime(2015, 11, 1, 1, 30), 'America/New_York', True) def testAmbiguousPositiveUTCOffset(self): self._test_ambiguous_time(datetime(2012, 4, 1, 2, 30), 'Australia/Sydney', True) def testUnambiguousNegativeUTCOffset(self): self._test_ambiguous_time(datetime(2015, 11, 1, 2, 30), 'America/New_York', False) def testUnambiguousPositiveUTCOffset(self): self._test_ambiguous_time(datetime(2012, 4, 1, 3, 30), 'Australia/Sydney', False) def testUnambiguousGapNegativeUTCOffset(self): # Imaginary time self._test_ambiguous_time(datetime(2011, 3, 13, 2, 30), 'America/New_York', False) def testUnambiguousGapPositiveUTCOffset(self): # Imaginary time self._test_ambiguous_time(datetime(2012, 10, 7, 2, 30), 'Australia/Sydney', False) def _test_imaginary_time(self, dt, tzid, exists): tzname = self._get_tzname(tzid) with self._gettz_context(tzname): tzi = self.gettz(tzname) self.assertEqual(tz.datetime_exists(dt, tz=tzi), exists) def testImaginaryNegativeUTCOffset(self): self._test_imaginary_time(datetime(2011, 3, 13, 2, 30), 'America/New_York', False) def testNotImaginaryNegativeUTCOffset(self): self._test_imaginary_time(datetime(2011, 3, 13, 1, 30), 'America/New_York', True) def testImaginaryPositiveUTCOffset(self): self._test_imaginary_time(datetime(2012, 10, 7, 2, 30), 'Australia/Sydney', False) def testNotImaginaryPositiveUTCOffset(self): self._test_imaginary_time(datetime(2012, 10, 7, 1, 30), 'Australia/Sydney', True) def testNotImaginaryFoldNegativeUTCOffset(self): self._test_imaginary_time(datetime(2015, 11, 1, 1, 30), 'America/New_York', True) def testNotImaginaryFoldPositiveUTCOffset(self): self._test_imaginary_time(datetime(2012, 4, 1, 3, 30), 'Australia/Sydney', True) @unittest.skip( "PEP 495 inter-zone comparisons are false for ambiguous times." ) def testEqualAmbiguousComparison(self): tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD0 = self.gettz(tzname) SYD1 = self.gettz(tzname) t0_u = datetime(2012, 3, 31, 14, 30, tzinfo=tz.UTC) # AEST t0_syd0 = t0_u.astimezone(SYD0) t0_syd1 = t0_u.astimezone(SYD1) # This is considered an "inter-zone comparison" because it's an # ambiguous datetime. self.assertEqual(t0_syd0, t0_syd1) class TzWinFoldMixin: def get_args(self, tzname): return (tzname, ) class context: def __init__(*args, **kwargs): pass def __enter__(*args, **kwargs): pass def __exit__(*args, **kwargs): pass def get_utc_transitions(self, tzi, year, gap): dston, dstoff = tzi.transitions(year) if gap: t_n = dston - timedelta(minutes=30) t0_u = t_n.replace(tzinfo=tzi).astimezone(tz.UTC) t1_u = t0_u + timedelta(hours=1) else: # Get 1 hour before the first ambiguous date t_n = dstoff - timedelta(minutes=30) t0_u = t_n.replace(tzinfo=tzi).astimezone(tz.UTC) t_n += timedelta(hours=1) # Naive ambiguous date t0_u = t0_u + timedelta(hours=1) # First ambiguous date t1_u = t0_u + timedelta(hours=1) # Second ambiguous date return t_n, t0_u, t1_u def testFoldPositiveUTCOffset(self): # Test that we can resolve ambiguous times tzname = 'AUS Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): # Calling fromutc() alters the tzfile object SYD = self.tzclass(*args) # Get the transition time in UTC from the object, because # Windows doesn't store historical info t_n, t0_u, t1_u = self.get_utc_transitions(SYD, 2012, False) # Using fresh tzfiles t0_syd = t0_u.astimezone(SYD) t1_syd = t1_u.astimezone(SYD) self.assertEqual(t0_syd.replace(tzinfo=None), t_n) self.assertEqual(t1_syd.replace(tzinfo=None), t_n) self.assertEqual(t0_syd.utcoffset(), timedelta(hours=11)) self.assertEqual(t1_syd.utcoffset(), timedelta(hours=10)) self.assertNotEqual(t0_syd.tzname(), t1_syd.tzname()) def testGapPositiveUTCOffset(self): # Test that we don't have a problem around gaps. tzname = 'AUS Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): SYD = self.tzclass(*args) t_n, t0_u, t1_u = self.get_utc_transitions(SYD, 2012, True) t0 = t0_u.astimezone(SYD) t1 = t1_u.astimezone(SYD) self.assertEqual(t0.replace(tzinfo=None), t_n) self.assertEqual(t1.replace(tzinfo=None), t_n + timedelta(hours=2)) self.assertEqual(t0.utcoffset(), timedelta(hours=10)) self.assertEqual(t1.utcoffset(), timedelta(hours=11)) def testFoldNegativeUTCOffset(self): # Test that we can resolve ambiguous times tzname = 'Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): TOR = self.tzclass(*args) t_n, t0_u, t1_u = self.get_utc_transitions(TOR, 2011, False) t0_tor = t0_u.astimezone(TOR) t1_tor = t1_u.astimezone(TOR) self.assertEqual(t0_tor.replace(tzinfo=None), t_n) self.assertEqual(t1_tor.replace(tzinfo=None), t_n) self.assertNotEqual(t0_tor.tzname(), t1_tor.tzname()) self.assertEqual(t0_tor.utcoffset(), timedelta(hours=-4.0)) self.assertEqual(t1_tor.utcoffset(), timedelta(hours=-5.0)) def testGapNegativeUTCOffset(self): # Test that we don't have a problem around gaps. tzname = 'Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): TOR = self.tzclass(*args) t_n, t0_u, t1_u = self.get_utc_transitions(TOR, 2011, True) t0 = t0_u.astimezone(TOR) t1 = t1_u.astimezone(TOR) self.assertEqual(t0.replace(tzinfo=None), t_n) self.assertEqual(t1.replace(tzinfo=None), t_n + timedelta(hours=2)) self.assertNotEqual(t0.tzname(), t1.tzname()) self.assertEqual(t0.utcoffset(), timedelta(hours=-5.0)) self.assertEqual(t1.utcoffset(), timedelta(hours=-4.0)) def testFoldIndependence(self): tzname = 'Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): NYC = self.tzclass(*args) UTC = tz.UTC hour = timedelta(hours=1) # Firmly 2015-11-01 0:30 EDT-4 t_n, t0_u, t1_u = self.get_utc_transitions(NYC, 2015, False) pre_dst = (t_n - hour).replace(tzinfo=NYC) # Currently, there's no way around the fact that this resolves to an # ambiguous date, which defaults to EST. I'm not hard-coding in the # answer, though, because the preferred behavior would be that this # results in a time on the EDT side. # Ambiguous between 2015-11-01 1:30 EDT-4 and 2015-11-01 1:30 EST-5 in_dst = pre_dst + hour in_dst_tzname_0 = in_dst.tzname() # Stash the tzname - EDT # Doing the arithmetic in UTC creates a date that is unambiguously # 2015-11-01 1:30 EDT-5 in_dst_via_utc = (pre_dst.astimezone(UTC) + 2*hour).astimezone(NYC) # Make sure we got the right folding behavior self.assertNotEqual(in_dst_via_utc.tzname(), in_dst_tzname_0) # Now check to make sure in_dst's tzname hasn't changed self.assertEqual(in_dst_tzname_0, in_dst.tzname()) def testInZoneFoldEquality(self): # Two datetimes in the same zone are considered to be equal if their # wall times are equal, even if they have different absolute times. tzname = 'Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): NYC = self.tzclass(*args) UTC = tz.UTC t_n, t0_u, t1_u = self.get_utc_transitions(NYC, 2011, False) dt0 = t_n.replace(tzinfo=NYC) dt1 = tz.enfold(dt0, fold=1) # Make sure these actually represent different times self.assertNotEqual(dt0.astimezone(UTC), dt1.astimezone(UTC)) # Test that they compare equal self.assertEqual(dt0, dt1) ### # Test Cases class TzUTCTest(unittest.TestCase): def testSingleton(self): UTC_0 = tz.tzutc() UTC_1 = tz.tzutc() self.assertIs(UTC_0, UTC_1) def testOffset(self): ct = datetime(2009, 4, 1, 12, 11, 13, tzinfo=tz.tzutc()) self.assertEqual(ct.utcoffset(), timedelta(seconds=0)) def testDst(self): ct = datetime(2009, 4, 1, 12, 11, 13, tzinfo=tz.tzutc()) self.assertEqual(ct.dst(), timedelta(seconds=0)) def testTzName(self): ct = datetime(2009, 4, 1, 12, 11, 13, tzinfo=tz.tzutc()) self.assertEqual(ct.tzname(), 'UTC') def testEquality(self): UTC0 = tz.tzutc() UTC1 = tz.tzutc() self.assertEqual(UTC0, UTC1) def testInequality(self): UTC = tz.tzutc() UTCp4 = tz.tzoffset('UTC+4', 14400) self.assertNotEqual(UTC, UTCp4) def testInequalityInteger(self): self.assertFalse(tz.tzutc() == 7) self.assertNotEqual(tz.tzutc(), 7) def testInequalityUnsupported(self): self.assertEqual(tz.tzutc(), ComparesEqual) def testRepr(self): UTC = tz.tzutc() self.assertEqual(repr(UTC), 'tzutc()') def testTimeOnlyUTC(self): # https://github.com/dateutil/dateutil/issues/132 # tzutc doesn't care tz_utc = tz.tzutc() self.assertEqual(dt_time(13, 20, tzinfo=tz_utc).utcoffset(), timedelta(0)) def testAmbiguity(self): # Pick an arbitrary datetime, this should always return False. dt = datetime(2011, 9, 1, 2, 30, tzinfo=tz.tzutc()) self.assertFalse(tz.datetime_ambiguous(dt)) @pytest.mark.tzoffset class TzOffsetTest(unittest.TestCase): def testTimedeltaOffset(self): est = tz.tzoffset('EST', timedelta(hours=-5)) est_s = tz.tzoffset('EST', -18000) self.assertEqual(est, est_s) def testTzNameNone(self): gmt5 = tz.tzoffset(None, -18000) # -5:00 self.assertIs(datetime(2003, 10, 26, 0, 0, tzinfo=gmt5).tzname(), None) def testTimeOnlyOffset(self): # tzoffset doesn't care tz_offset = tz.tzoffset('+3', 3600) self.assertEqual(dt_time(13, 20, tzinfo=tz_offset).utcoffset(), timedelta(seconds=3600)) def testTzOffsetRepr(self): tname = 'EST' tzo = tz.tzoffset(tname, -5 * 3600) self.assertEqual(repr(tzo), "tzoffset(" + repr(tname) + ", -18000)") def testEquality(self): utc = tz.tzoffset('UTC', 0) gmt = tz.tzoffset('GMT', 0) self.assertEqual(utc, gmt) def testUTCEquality(self): utc = tz.UTC o_utc = tz.tzoffset('UTC', 0) self.assertEqual(utc, o_utc) self.assertEqual(o_utc, utc) def testInequalityInvalid(self): tzo = tz.tzoffset('-3', -3 * 3600) self.assertFalse(tzo == -3) self.assertNotEqual(tzo, -3) def testInequalityUnsupported(self): tzo = tz.tzoffset('-5', -5 * 3600) self.assertTrue(tzo == ComparesEqual) self.assertFalse(tzo != ComparesEqual) self.assertEqual(tzo, ComparesEqual) def testAmbiguity(self): # Pick an arbitrary datetime, this should always return False. dt = datetime(2011, 9, 1, 2, 30, tzinfo=tz.tzoffset("EST", -5 * 3600)) self.assertFalse(tz.datetime_ambiguous(dt)) def testTzOffsetInstance(self): tz1 = tz.tzoffset.instance('EST', timedelta(hours=-5)) tz2 = tz.tzoffset.instance('EST', timedelta(hours=-5)) assert tz1 is not tz2 def testTzOffsetSingletonDifferent(self): tz1 = tz.tzoffset('EST', timedelta(hours=-5)) tz2 = tz.tzoffset('EST', -18000) assert tz1 is tz2 @pytest.mark.smoke @pytest.mark.tzoffset def test_tzoffset_weakref(): UTC1 = tz.tzoffset('UTC', 0) UTC_ref = weakref.ref(tz.tzoffset('UTC', 0)) UTC1 is UTC_ref() del UTC1 gc.collect() assert UTC_ref() is not None # Should be in the strong cache assert UTC_ref() is tz.tzoffset('UTC', 0) # Fill the strong cache with other items for offset in range(5,15): tz.tzoffset('RandomZone', offset) gc.collect() assert UTC_ref() is None assert UTC_ref() is not tz.tzoffset('UTC', 0) @pytest.mark.tzoffset @pytest.mark.parametrize('args', [ ('UTC', 0), ('EST', -18000), ('EST', timedelta(hours=-5)), (None, timedelta(hours=3)), ]) def test_tzoffset_singleton(args): tz1 = tz.tzoffset(*args) tz2 = tz.tzoffset(*args) assert tz1 is tz2 @pytest.mark.tzoffset def test_tzoffset_sub_minute(): delta = timedelta(hours=12, seconds=30) test_datetime = datetime(2000, 1, 1, tzinfo=tz.tzoffset(None, delta)) assert test_datetime.utcoffset() == delta @pytest.mark.tzlocal class TzLocalTest(unittest.TestCase): def testEquality(self): tz1 = tz.tzlocal() tz2 = tz.tzlocal() # Explicitly calling == and != here to ensure the operators work self.assertTrue(tz1 == tz2) self.assertFalse(tz1 != tz2) def testInequalityFixedOffset(self): tzl = tz.tzlocal() tzos = tz.tzoffset('LST', tzl._std_offset.total_seconds()) tzod = tz.tzoffset('LDT', tzl._std_offset.total_seconds()) self.assertFalse(tzl == tzos) self.assertFalse(tzl == tzod) self.assertTrue(tzl != tzos) self.assertTrue(tzl != tzod) def testInequalityInvalid(self): tzl = tz.tzlocal() self.assertTrue(tzl != 1) self.assertFalse(tzl == 1) # TODO: Use some sort of universal local mocking so that it's clear # that we're expecting tzlocal to *not* be Pacific/Kiritimati LINT = tz.gettz('Pacific/Kiritimati') self.assertTrue(tzl != LINT) self.assertFalse(tzl == LINT) def testInequalityUnsupported(self): tzl = tz.tzlocal() self.assertTrue(tzl == ComparesEqual) self.assertFalse(tzl != ComparesEqual) def testRepr(self): tzl = tz.tzlocal() self.assertEqual(repr(tzl), 'tzlocal()') @pytest.mark.parametrize('args,kwargs', [ (('EST', -18000), {}), (('EST', timedelta(hours=-5)), {}), (('EST',), {'offset': -18000}), (('EST',), {'offset': timedelta(hours=-5)}), (tuple(), {'name': 'EST', 'offset': -18000}) ]) def test_tzoffset_is(args, kwargs): tz_ref = tz.tzoffset('EST', -18000) assert tz.tzoffset(*args, **kwargs) is tz_ref def test_tzoffset_is_not(): assert tz.tzoffset('EDT', -14400) is not tz.tzoffset('EST', -18000) @pytest.mark.tzlocal @unittest.skipIf(IS_WIN, "requires Unix") class TzLocalNixTest(unittest.TestCase, TzFoldMixin): # This is a set of tests for `tzlocal()` on *nix systems # POSIX string indicating change to summer time on the 2nd Sunday in March # at 2AM, and ending the 1st Sunday in November at 2AM. (valid >= 2007) TZ_EST = 'EST+5EDT,M3.2.0/2,M11.1.0/2' # POSIX string for AEST/AEDT (valid >= 2008) TZ_AEST = 'AEST-10AEDT,M10.1.0/2,M4.1.0/3' # POSIX string for BST/GMT TZ_LON = 'GMT0BST,M3.5.0,M10.5.0' # POSIX string for UTC UTC = 'UTC' def gettz(self, tzname): # Actual time zone changes are handled by the _gettz_context function return tz.tzlocal() def _gettz_context(self, tzname): tzname_map = {'Australia/Sydney': self.TZ_AEST, 'America/Toronto': self.TZ_EST, 'America/New_York': self.TZ_EST, 'Europe/London': self.TZ_LON} return TZEnvContext(tzname_map.get(tzname, tzname)) def _testTzFunc(self, tzval, func, std_val, dst_val): """ This generates tests about how the behavior of a function ``func`` changes between STD and DST (e.g. utcoffset, tzname, dst). It assume that DST starts the 2nd Sunday in March and ends the 1st Sunday in November """ with TZEnvContext(tzval): dt1 = datetime(2015, 2, 1, 12, 0, tzinfo=tz.tzlocal()) # STD dt2 = datetime(2015, 5, 1, 12, 0, tzinfo=tz.tzlocal()) # DST self.assertEqual(func(dt1), std_val) self.assertEqual(func(dt2), dst_val) def _testTzName(self, tzval, std_name, dst_name): func = datetime.tzname self._testTzFunc(tzval, func, std_name, dst_name) def testTzNameDST(self): # Test tzname in a zone with DST self._testTzName(self.TZ_EST, 'EST', 'EDT') def testTzNameUTC(self): # Test tzname in a zone without DST self._testTzName(self.UTC, 'UTC', 'UTC') def _testOffset(self, tzval, std_off, dst_off): func = datetime.utcoffset self._testTzFunc(tzval, func, std_off, dst_off) def testOffsetDST(self): self._testOffset(self.TZ_EST, timedelta(hours=-5), timedelta(hours=-4)) def testOffsetUTC(self): self._testOffset(self.UTC, timedelta(0), timedelta(0)) def _testDST(self, tzval, dst_dst): func = datetime.dst std_dst = timedelta(0) self._testTzFunc(tzval, func, std_dst, dst_dst) def testDSTDST(self): self._testDST(self.TZ_EST, timedelta(hours=1)) def testDSTUTC(self): self._testDST(self.UTC, timedelta(0)) def testTimeOnlyOffsetLocalUTC(self): with TZEnvContext(self.UTC): self.assertEqual(dt_time(13, 20, tzinfo=tz.tzlocal()).utcoffset(), timedelta(0)) def testTimeOnlyOffsetLocalDST(self): with TZEnvContext(self.TZ_EST): self.assertIs(dt_time(13, 20, tzinfo=tz.tzlocal()).utcoffset(), None) def testTimeOnlyDSTLocalUTC(self): with TZEnvContext(self.UTC): self.assertEqual(dt_time(13, 20, tzinfo=tz.tzlocal()).dst(), timedelta(0)) def testTimeOnlyDSTLocalDST(self): with TZEnvContext(self.TZ_EST): self.assertIs(dt_time(13, 20, tzinfo=tz.tzlocal()).dst(), None) def testUTCEquality(self): with TZEnvContext(self.UTC): assert tz.tzlocal() == tz.UTC # TODO: Maybe a better hack than this? def mark_tzlocal_nix(f): marks = [ pytest.mark.tzlocal, pytest.mark.skipif(IS_WIN, reason='requires Unix'), ] for mark in reversed(marks): f = mark(f) return f @mark_tzlocal_nix @pytest.mark.parametrize('tzvar', ['UTC', 'GMT0', 'UTC0']) def test_tzlocal_utc_equal(tzvar): with TZEnvContext(tzvar): assert tz.tzlocal() == tz.UTC @mark_tzlocal_nix @pytest.mark.parametrize('tzvar', [ 'Europe/London', 'America/New_York', 'GMT0BST', 'EST5EDT']) def test_tzlocal_utc_unequal(tzvar): with TZEnvContext(tzvar): assert tz.tzlocal() != tz.UTC @mark_tzlocal_nix def test_tzlocal_local_time_trim_colon(): with TZEnvContext(':/etc/localtime'): assert tz.gettz() is not None @mark_tzlocal_nix @pytest.mark.parametrize('tzvar, tzoff', [ ('EST5', tz.tzoffset('EST', -18000)), ('GMT0', tz.tzoffset('GMT', 0)), ('YAKT-9', tz.tzoffset('YAKT', timedelta(hours=9))), ('JST-9', tz.tzoffset('JST', timedelta(hours=9))), ]) def test_tzlocal_offset_equal(tzvar, tzoff): with TZEnvContext(tzvar): # Including both to test both __eq__ and __ne__ assert tz.tzlocal() == tzoff assert not (tz.tzlocal() != tzoff) @mark_tzlocal_nix @pytest.mark.parametrize('tzvar, tzoff', [ ('EST5EDT', tz.tzoffset('EST', -18000)), ('GMT0BST', tz.tzoffset('GMT', 0)), ('EST5', tz.tzoffset('EST', -14400)), ('YAKT-9', tz.tzoffset('JST', timedelta(hours=9))), ('JST-9', tz.tzoffset('YAKT', timedelta(hours=9))), ]) def test_tzlocal_offset_unequal(tzvar, tzoff): with TZEnvContext(tzvar): # Including both to test both __eq__ and __ne__ assert tz.tzlocal() != tzoff assert not (tz.tzlocal() == tzoff) @pytest.mark.gettz class GettzTest(TzSourceMixin, unittest.TestCase, TzFoldMixin): gettz = staticmethod(tz.gettz) def testGettz(self): # bug 892569 str(self.gettz("Etc/UTC")) def testGetTzEquality(self): self.assertEqual(self.gettz("Etc/UTC"), self.gettz("Etc/UTC")) def testTimeOnlyGettz(self): # gettz returns None tz_get = self.gettz('Europe/Minsk') self.assertIs(dt_time(13, 20, tzinfo=tz_get).utcoffset(), None) def testTimeOnlyGettzDST(self): # gettz returns None tz_get = self.gettz('Europe/Minsk') self.assertIs(dt_time(13, 20, tzinfo=tz_get).dst(), None) def testTimeOnlyGettzTzName(self): tz_get = self.gettz('Europe/Minsk') self.assertIs(dt_time(13, 20, tzinfo=tz_get).tzname(), None) def testTimeOnlyFormatZ(self): tz_get = self.gettz('Europe/Minsk') t = dt_time(13, 20, tzinfo=tz_get) self.assertEqual(t.strftime('%H%M%Z'), '1320') def testPortugalDST(self): # In 1996, Portugal changed from CET to WET PORTUGAL = self.gettz("Europe/Lisbon") t_cet = datetime(1996, 3, 31, 1, 59, tzinfo=PORTUGAL) self.assertEqual(t_cet.tzname(), 'CET') self.assertEqual(t_cet.utcoffset(), timedelta(hours=1)) self.assertEqual(t_cet.dst(), timedelta(0)) t_west = datetime(1996, 3, 31, 2, 1, tzinfo=PORTUGAL) self.assertEqual(t_west.tzname(), 'WEST') self.assertEqual(t_west.utcoffset(), timedelta(hours=1)) self.assertEqual(t_west.dst(), timedelta(hours=1)) def testGettzCacheTzFile(self): NYC1 = tz.gettz('America/New_York') NYC2 = tz.gettz('America/New_York') assert NYC1 is NYC2 @pytest.mark.xfail( IS_WIN and ("/" in os.environ.get("TZ", "")), reason="On Windows IANA zones are currently always singletons", ) def testGettzCacheTzLocal(self): local1 = tz.gettz() local2 = tz.gettz() assert local1 is not local2 def test_key_attribute(self): # Also tested more thoroughly in the property tests. NYC = tz.gettz("America/New_York") assert NYC.key == "America/New_York" @pytest.mark.gettz class GettzTzdataTest(GettzTest): tz_source = "tzdata" # Links from the "backward" file in the tz database, which some builds leave # out, and which may be removed in the future. LINKS = [ ("US/Eastern", "America/New_York"), ("US/Pacific", "America/Los_Angeles"), ("Portugal", "Europe/Lisbon"), ("Europe/Kiev", "Europe/Kyiv"), ("Australia/Canberra", "Australia/Sydney"), ("Australia/Currie", "Australia/Hobart"), ("Europe/Monaco", "Europe/Paris"), ("UTC", "Etc/UTC"), ("GMT", "Etc/GMT"), ] @pytest.mark.gettz @pytest.mark.parametrize("link, target", LINKS) def test_gettz_link(tz_source, link, target): """A link behaves like its target, but keeps its own key.""" if link not in tz.available_iana_timezones(): pytest.skip("%s is not in this time zone data" % link) link_zone = tz.gettz(link) target_zone = tz.gettz(target) assert isinstance(link_zone, tz.tzfile) assert isinstance(target_zone, tz.tzfile) assert link_zone == target_zone assert link_zone.key == link assert target_zone.key == target @pytest.mark.gettz def test_gettz_same_result_for_none_and_empty_string(): local_from_none = tz.gettz() local_from_empty_string = tz.gettz("") assert local_from_none is not None assert local_from_empty_string is not None assert local_from_none == local_from_empty_string @pytest.mark.gettz @pytest.mark.parametrize('badzone', [ 'Fake.Region/Abcdefghijklmnop', # Violates several tz project name rules ]) def test_gettz_badzone(badzone): # Make sure passing a bad TZ string to gettz returns None (GH #800) tzi = tz.gettz(badzone) assert tzi is None @pytest.mark.gettz def test_gettz_badzone_unicode(): # Make sure a unicode string can be passed to TZ (GH #802) # When fixed, combine this with test_gettz_badzone tzi = tz.gettz('ðŸ�¼') assert tzi is None @pytest.mark.gettz @pytest.mark.parametrize( "badzone,exc_reason", [ pytest.param( b"America/New_York", ".*should be str, not bytes.*", id="bytes on Python 3", ), pytest.param( object(), None, id="no startswith()", marks=[ pytest.mark.xfail(reason="AttributeError instead of TypeError", raises=AttributeError), ], ), ], ) def test_gettz_zone_wrong_type(badzone, exc_reason): with pytest.raises(TypeError, match=exc_reason): tz.gettz(badzone) @pytest.mark.gettz def test_gettz_cache_clear(): NYC1 = tz.gettz('America/New_York') tz.gettz.cache_clear() NYC2 = tz.gettz('America/New_York') assert NYC1 is not NYC2 @pytest.mark.gettz def test_gettz_set_cache_size(): tz.gettz.cache_clear() tz.gettz.set_cache_size(3) PARIS_ref = weakref.ref(tz.gettz("Europe/Paris")) EASTER_ref = weakref.ref(tz.gettz("Pacific/Easter")) HOBART_ref = weakref.ref(tz.gettz("Australia/Hobart")) gc.collect() assert PARIS_ref() is not None assert EASTER_ref() is not None assert HOBART_ref() is not None tz.gettz.set_cache_size(2) gc.collect() assert PARIS_ref() is None @pytest.mark.smoke @pytest.mark.gettz def test_gettz_weakref(): tz.gettz.cache_clear() tz.gettz.set_cache_size(2) NYC1 = tz.gettz('America/New_York') NYC_ref = weakref.ref(tz.gettz('America/New_York')) assert NYC1 is NYC_ref() del NYC1 gc.collect() assert NYC_ref() is not None # Should still be in the strong cache assert tz.gettz('America/New_York') is NYC_ref() # Populate strong cache with other timezones tz.gettz("Europe/Paris") tz.gettz("Pacific/Easter") tz.gettz("Australia/Hobart") gc.collect() assert NYC_ref() is None # Should have been pushed out assert tz.gettz('America/New_York') is not NYC_ref() @requires_tzdata class ZoneInfoGettzTest(GettzTest): # This reads the tzdata package through dateutil.zoneinfo directly tz_source = None def gettz(self, name): zoneinfo_file = zoneinfo.get_zonefile_instance() return zoneinfo_file.get(name) def testZoneInfoFileStart1(self): tzc = self.gettz("EST5EDT") self.assertEqual( datetime(2003, 4, 6, 1, 59, tzinfo=tzc).tzname(), "EST", MISSING_TARBALL, ) self.assertEqual( tz.enfold(datetime(2003, 4, 6, 2, tzinfo=tzc), fold=0).tzname(), "EST", ) self.assertEqual( tz.enfold(datetime(2003, 4, 6, 2, tzinfo=tzc), fold=1).tzname(), "EDT", ) self.assertEqual(datetime(2003, 4, 6, 3, 0, tzinfo=tzc).tzname(), "EDT") def testZoneInfoFileEnd1(self): tzc = self.gettz("EST5EDT") self.assertEqual(datetime(2003, 10, 26, 0, 59, tzinfo=tzc).tzname(), "EDT", MISSING_TARBALL) end_est = tz.enfold(datetime(2003, 10, 26, 1, 0, tzinfo=tzc), fold=1) self.assertEqual(end_est.tzname(), "EST") def testZoneInfoOffsetSignal(self): utc = self.gettz("UTC") nyc = self.gettz("America/New_York") self.assertNotEqual(utc, None, MISSING_TARBALL) self.assertNotEqual(nyc, None) t0 = datetime(2007, 11, 4, 0, 30, tzinfo=nyc) t1 = t0.astimezone(utc) t2 = t1.astimezone(nyc) self.assertEqual(t0, t2) self.assertEqual(nyc.dst(t0), timedelta(hours=1)) def testZoneInfoCopy(self): # copy.copy() called on a ZoneInfo file was returning the same instance CHI = self.gettz('America/Chicago') CHI_COPY = copy.copy(CHI) self.assertIsNot(CHI, CHI_COPY) self.assertEqual(CHI, CHI_COPY) def testZoneInfoDeepCopy(self): CHI = self.gettz('America/Chicago') CHI_COPY = copy.deepcopy(CHI) self.assertIsNot(CHI, CHI_COPY) self.assertEqual(CHI, CHI_COPY) def testZoneInfoInstanceCaching(self): zif_0 = zoneinfo.get_zonefile_instance() zif_1 = zoneinfo.get_zonefile_instance() self.assertIs(zif_0, zif_1) def testZoneInfoNewInstance(self): zif_0 = zoneinfo.get_zonefile_instance() zif_1 = zoneinfo.get_zonefile_instance(new_instance=True) zif_2 = zoneinfo.get_zonefile_instance() self.assertIsNot(zif_0, zif_1) self.assertIs(zif_1, zif_2) def testZoneInfoDeprecated(self): with pytest.warns(DeprecationWarning): zoneinfo.gettz('US/Eastern') def testZoneInfoMetadataDeprecated(self): with pytest.warns(DeprecationWarning): zoneinfo.gettz_db_metadata() def testZoneInfoMetadataFreshInstance(self): # gettz_db_metadata must be able to create the module-level # instance itself if gettz has not been called first. old_instances = list(zoneinfo._CLASS_ZONE_INSTANCE) del zoneinfo._CLASS_ZONE_INSTANCE[:] try: with pytest.warns(DeprecationWarning): metadata = zoneinfo.gettz_db_metadata() finally: zoneinfo._CLASS_ZONE_INSTANCE[:] = old_instances assert metadata["tzversion"] class TZRangeTest(unittest.TestCase, TzFoldMixin): TZ_EST = tz.tzrange('EST', timedelta(hours=-5), 'EDT', timedelta(hours=-4), start=relativedelta(month=3, day=1, hour=2, weekday=SU(+2)), end=relativedelta(month=11, day=1, hour=1, weekday=SU(+1))) TZ_AEST = tz.tzrange('AEST', timedelta(hours=10), 'AEDT', timedelta(hours=11), start=relativedelta(month=10, day=1, hour=2, weekday=SU(+1)), end=relativedelta(month=4, day=1, hour=2, weekday=SU(+1))) TZ_LON = tz.tzrange('GMT', timedelta(hours=0), 'BST', timedelta(hours=1), start=relativedelta(month=3, day=31, weekday=SU(-1), hours=2), end=relativedelta(month=10, day=31, weekday=SU(-1), hours=1)) # POSIX string for UTC UTC = 'UTC' def gettz(self, tzname): tzname_map = {'Australia/Sydney': self.TZ_AEST, 'America/Toronto': self.TZ_EST, 'America/New_York': self.TZ_EST, 'Europe/London': self.TZ_LON} return tzname_map[tzname] def testRangeCmp1(self): self.assertEqual(tz.tzstr("EST5EDT"), tz.tzrange("EST", -18000, "EDT", -14400, relativedelta(hours=+2, month=4, day=1, weekday=SU(+1)), relativedelta(hours=+1, month=10, day=31, weekday=SU(-1)))) def testRangeCmp2(self): self.assertEqual(tz.tzstr("EST5EDT"), tz.tzrange("EST", -18000, "EDT")) def testRangeOffsets(self): TZR = tz.tzrange('EST', -18000, 'EDT', -14400, start=relativedelta(hours=2, month=4, day=1, weekday=SU(+2)), end=relativedelta(hours=1, month=10, day=31, weekday=SU(-1))) dt_std = datetime(2014, 4, 11, 12, 0, tzinfo=TZR) # STD dt_dst = datetime(2016, 4, 11, 12, 0, tzinfo=TZR) # DST dst_zero = timedelta(0) dst_hour = timedelta(hours=1) std_offset = timedelta(hours=-5) dst_offset = timedelta(hours=-4) # Check dst() self.assertEqual(dt_std.dst(), dst_zero) self.assertEqual(dt_dst.dst(), dst_hour) # Check utcoffset() self.assertEqual(dt_std.utcoffset(), std_offset) self.assertEqual(dt_dst.utcoffset(), dst_offset) # Check tzname self.assertEqual(dt_std.tzname(), 'EST') self.assertEqual(dt_dst.tzname(), 'EDT') def testTimeOnlyRangeFixed(self): # This is a fixed-offset zone, so tzrange allows this tz_range = tz.tzrange('dflt', stdoffset=timedelta(hours=-3)) self.assertEqual(dt_time(13, 20, tzinfo=tz_range).utcoffset(), timedelta(hours=-3)) def testTimeOnlyRange(self): # tzrange returns None because this zone has DST tz_range = tz.tzrange('EST', timedelta(hours=-5), 'EDT', timedelta(hours=-4)) self.assertIs(dt_time(13, 20, tzinfo=tz_range).utcoffset(), None) def testBrokenIsDstHandling(self): # tzrange._isdst() was using a date() rather than a datetime(). # Issue reported by Lennart Regebro. dt = datetime(2007, 8, 6, 4, 10, tzinfo=tz.UTC) self.assertEqual(dt.astimezone(tz=tz.gettz("GMT+2")), datetime(2007, 8, 6, 6, 10, tzinfo=tz.tzstr("GMT+2"))) def testRangeTimeDelta(self): # Test that tzrange can be specified with a timedelta instead of an int. EST5EDT_td = tz.tzrange('EST', timedelta(hours=-5), 'EDT', timedelta(hours=-4)) EST5EDT_sec = tz.tzrange('EST', -18000, 'EDT', -14400) self.assertEqual(EST5EDT_td, EST5EDT_sec) def testRangeEquality(self): TZR1 = tz.tzrange('EST', -18000, 'EDT', -14400) # Standard abbreviation different TZR2 = tz.tzrange('ET', -18000, 'EDT', -14400) self.assertNotEqual(TZR1, TZR2) # DST abbreviation different TZR3 = tz.tzrange('EST', -18000, 'EMT', -14400) self.assertNotEqual(TZR1, TZR3) # STD offset different TZR4 = tz.tzrange('EST', -14000, 'EDT', -14400) self.assertNotEqual(TZR1, TZR4) # DST offset different TZR5 = tz.tzrange('EST', -18000, 'EDT', -18000) self.assertNotEqual(TZR1, TZR5) # Start delta different TZR6 = tz.tzrange('EST', -18000, 'EDT', -14400, start=relativedelta(hours=+1, month=3, day=1, weekday=SU(+2))) self.assertNotEqual(TZR1, TZR6) # End delta different TZR7 = tz.tzrange('EST', -18000, 'EDT', -14400, end=relativedelta(hours=+1, month=11, day=1, weekday=SU(+2))) self.assertNotEqual(TZR1, TZR7) def testRangeInequalityUnsupported(self): TZR = tz.tzrange('EST', -18000, 'EDT', -14400) self.assertFalse(TZR == 4) self.assertTrue(TZR == ComparesEqual) self.assertFalse(TZR != ComparesEqual) @pytest.mark.tzstr class TZStrTest(unittest.TestCase, TzFoldMixin): # POSIX string indicating change to summer time on the 2nd Sunday in March # at 2AM, and ending the 1st Sunday in November at 2AM. (valid >= 2007) TZ_EST = 'EST+5EDT,M3.2.0/2,M11.1.0/2' # POSIX string for AEST/AEDT (valid >= 2008) TZ_AEST = 'AEST-10AEDT,M10.1.0/2,M4.1.0/3' # POSIX string for GMT/BST TZ_LON = 'GMT0BST,M3.5.0,M10.5.0' def gettz(self, tzname): # Actual time zone changes are handled by the _gettz_context function tzname_map = {'Australia/Sydney': self.TZ_AEST, 'America/Toronto': self.TZ_EST, 'America/New_York': self.TZ_EST, 'Europe/London': self.TZ_LON} return tz.tzstr(tzname_map[tzname]) def testStrTransition(self): # Check the abbreviation on either side of the DST transition. self.assertEqual( datetime(2003, 4, 6, 1, 59, tzinfo=tz.tzstr("EST5EDT")).tzname(), "EST", ) self.assertEqual( datetime(2003, 4, 6, 2, 00, tzinfo=tz.tzstr("EST5EDT")).tzname(), "EDT", ) def testStrInequality(self): TZS1 = tz.tzstr('EST5EDT4') # Standard abbreviation different TZS2 = tz.tzstr('ET5EDT4') self.assertNotEqual(TZS1, TZS2) # DST abbreviation different TZS3 = tz.tzstr('EST5EMT') self.assertNotEqual(TZS1, TZS3) # STD offset different TZS4 = tz.tzstr('EST4EDT4') self.assertNotEqual(TZS1, TZS4) # DST offset different TZS5 = tz.tzstr('EST5EDT3') self.assertNotEqual(TZS1, TZS5) def testStrInequalityStartEnd(self): TZS1 = tz.tzstr('EST5EDT4') # Start delta different TZS2 = tz.tzstr('EST5EDT4,M4.2.0/02:00:00,M10-5-0/02:00') self.assertNotEqual(TZS1, TZS2) # End delta different TZS3 = tz.tzstr('EST5EDT4,M4.2.0/02:00:00,M11-5-0/02:00') self.assertNotEqual(TZS1, TZS3) def testPosixOffset(self): TZ1 = tz.tzstr('UTC-3') self.assertEqual(datetime(2015, 1, 1, tzinfo=TZ1).utcoffset(), timedelta(hours=-3)) TZ2 = tz.tzstr('UTC-3', posix_offset=True) self.assertEqual(datetime(2015, 1, 1, tzinfo=TZ2).utcoffset(), timedelta(hours=+3)) def testStrInequalityUnsupported(self): TZS = tz.tzstr('EST5EDT') self.assertFalse(TZS == 4) self.assertTrue(TZS == ComparesEqual) self.assertFalse(TZS != ComparesEqual) def testTzStrRepr(self): TZS1 = tz.tzstr('EST5EDT4') TZS2 = tz.tzstr('EST') self.assertEqual(repr(TZS1), "tzstr(" + repr('EST5EDT4') + ")") self.assertEqual(repr(TZS2), "tzstr(" + repr('EST') + ")") def testTzStrFailure(self): with self.assertRaises(ValueError): tz.tzstr('InvalidString;439999') def testTzStrSingleton(self): tz1 = tz.tzstr('EST5EDT') tz2 = tz.tzstr('CST4CST') tz3 = tz.tzstr('EST5EDT') self.assertIsNot(tz1, tz2) self.assertIs(tz1, tz3) def testTzStrSingletonPosix(self): tz_t1 = tz.tzstr('GMT+3', posix_offset=True) tz_f1 = tz.tzstr('GMT+3', posix_offset=False) tz_t2 = tz.tzstr('GMT+3', posix_offset=True) tz_f2 = tz.tzstr('GMT+3', posix_offset=False) self.assertIs(tz_t1, tz_t2) self.assertIsNot(tz_t1, tz_f1) self.assertIs(tz_f1, tz_f2) def testTzStrInstance(self): tz1 = tz.tzstr('EST5EDT') tz2 = tz.tzstr.instance('EST5EDT') tz3 = tz.tzstr.instance('EST5EDT') assert tz1 is not tz2 assert tz2 is not tz3 # Ensure that these still are all the same zone assert tz1 == tz2 == tz3 @pytest.mark.smoke @pytest.mark.tzstr def test_tzstr_weakref(): tz_t1 = tz.tzstr('EST5EDT') tz_t2_ref = weakref.ref(tz.tzstr('EST5EDT')) assert tz_t1 is tz_t2_ref() del tz_t1 gc.collect() assert tz_t2_ref() is not None assert tz.tzstr('EST5EDT') is tz_t2_ref() for offset in range(5,15): tz.tzstr('GMT+{}'.format(offset)) gc.collect() assert tz_t2_ref() is None assert tz.tzstr('EST5EDT') is not tz_t2_ref() @pytest.mark.tzstr @pytest.mark.parametrize('tz_str,expected', [ # From https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html ('', tz.tzrange(None)), # TODO: Should change this so tz.tzrange('') works ('EST+5EDT,M3.2.0/2,M11.1.0/12', tz.tzrange('EST', -18000, 'EDT', -14400, start=relativedelta(month=3, day=1, weekday=SU(2), hours=2), end=relativedelta(month=11, day=1, weekday=SU(1), hours=11))), ('WART4WARST,J1/0,J365/25', # This is DST all year, Western Argentina Summer Time tz.tzrange('WART', timedelta(hours=-4), 'WARST', start=relativedelta(month=1, day=1, hours=0), end=relativedelta(month=12, day=31, days=1))), ('IST-2IDT,M3.4.4/26,M10.5.0', # Israel Standard / Daylight Time tz.tzrange('IST', timedelta(hours=2), 'IDT', start=relativedelta(month=3, day=1, weekday=TH(4), days=1, hours=2), end=relativedelta(month=10, day=31, weekday=SU(-1), hours=1))), ('WGT3WGST,M3.5.0/2,M10.5.0/1', tz.tzrange('WGT', timedelta(hours=-3), 'WGST', start=relativedelta(month=3, day=31, weekday=SU(-1), hours=2), end=relativedelta(month=10, day=31, weekday=SU(-1), hours=0))), # Different offset specifications ('WGT0300WGST', tz.tzrange('WGT', timedelta(hours=-3), 'WGST')), ('WGT03:00WGST', tz.tzrange('WGT', timedelta(hours=-3), 'WGST')), ('AEST-1100AEDT', tz.tzrange('AEST', timedelta(hours=11), 'AEDT')), ('AEST-11:00AEDT', tz.tzrange('AEST', timedelta(hours=11), 'AEDT')), # Different time formats ('EST5EDT,M3.2.0/4:00,M11.1.0/3:00', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(month=3, day=1, weekday=SU(2), hours=4), end=relativedelta(month=11, day=1, weekday=SU(1), hours=2))), ('EST5EDT,M3.2.0/04:00,M11.1.0/03:00', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(month=3, day=1, weekday=SU(2), hours=4), end=relativedelta(month=11, day=1, weekday=SU(1), hours=2))), ('EST5EDT,M3.2.0/0400,M11.1.0/0300', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(month=3, day=1, weekday=SU(2), hours=4), end=relativedelta(month=11, day=1, weekday=SU(1), hours=2))), ]) def test_valid_GNU_tzstr(tz_str, expected): tzi = tz.tzstr(tz_str) assert tzi == expected @pytest.mark.tzstr @pytest.mark.parametrize('tz_str, expected', [ ('EST5EDT,5,4,0,7200,11,3,0,7200', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(month=5, day=1, weekday=SU(+4), hours=+2), end=relativedelta(month=11, day=1, weekday=SU(+3), hours=+1))), ('EST5EDT,5,-4,0,7200,11,3,0,7200', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(hours=+2, month=5, day=31, weekday=SU(-4)), end=relativedelta(hours=+1, month=11, day=1, weekday=SU(+3)))), ('EST5EDT,5,4,0,7200,11,-3,0,7200', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(hours=+2, month=5, day=1, weekday=SU(+4)), end=relativedelta(hours=+1, month=11, day=31, weekday=SU(-3)))), ('EST5EDT,5,4,0,7200,11,-3,0,7200,3600', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(hours=+2, month=5, day=1, weekday=SU(+4)), end=relativedelta(hours=+1, month=11, day=31, weekday=SU(-3)))), ('EST5EDT,5,4,0,7200,11,-3,0,7200,3600', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(hours=+2, month=5, day=1, weekday=SU(+4)), end=relativedelta(hours=+1, month=11, day=31, weekday=SU(-3)))), ('EST5EDT,5,4,0,7200,11,-3,0,7200,-3600', tz.tzrange('EST', timedelta(hours=-5), 'EDT', timedelta(hours=-6), start=relativedelta(hours=+2, month=5, day=1, weekday=SU(+4)), end=relativedelta(hours=+3, month=11, day=31, weekday=SU(-3)))), ('EST5EDT,5,4,0,7200,11,-3,0,7200,+7200', tz.tzrange('EST', timedelta(hours=-5), 'EDT', timedelta(hours=-3), start=relativedelta(hours=+2, month=5, day=1, weekday=SU(+4)), end=relativedelta(hours=0, month=11, day=31, weekday=SU(-3)))), ('EST5EDT,5,4,0,7200,11,-3,0,7200,+3600', tz.tzrange('EST', timedelta(hours=-5), 'EDT', start=relativedelta(hours=+2, month=5, day=1, weekday=SU(+4)), end=relativedelta(hours=+1, month=11, day=31, weekday=SU(-3)))), ]) def test_valid_dateutil_format(tz_str, expected): # This tests the dateutil-specific format that is used widely in the tests # and examples. It is unclear where this format originated from. with pytest.warns(tz.DeprecatedTzFormatWarning): tzi = tz.tzstr.instance(tz_str) assert tzi == expected @pytest.mark.tzstr @pytest.mark.parametrize('tz_str', [ 'hdfiughdfuig,dfughdfuigpu87ñ::', ',dfughdfuigpu87ñ::', '-1:WART4WARST,J1,J365/25', 'WART4WARST,J1,J365/-25', 'IST-2IDT,M3.4.-1/26,M10.5.0', 'IST-2IDT,M3,2000,1/26,M10,5,0' ]) def test_invalid_GNU_tzstr(tz_str): with pytest.raises(ValueError): tz.tzstr(tz_str) # Different representations of the same default rule set DEFAULT_TZSTR_RULES_EQUIV_2003 = [ 'EST5EDT', 'EST5EDT4,M4.1.0/02:00:00,M10-5-0/02:00', 'EST5EDT4,95/02:00:00,298/02:00', 'EST5EDT4,J96/02:00:00,J299/02:00', 'EST5EDT4,J96/02:00:00,J299/02' ] @pytest.mark.tzstr @pytest.mark.parametrize('tz_str', DEFAULT_TZSTR_RULES_EQUIV_2003) def test_tzstr_default_start(tz_str): tzi = tz.tzstr(tz_str) dt_std = datetime(2003, 4, 6, 1, 59, tzinfo=tzi) dt_dst = datetime(2003, 4, 6, 2, 00, tzinfo=tzi) assert get_timezone_tuple(dt_std) == EST_TUPLE assert get_timezone_tuple(dt_dst) == EDT_TUPLE @pytest.mark.tzstr @pytest.mark.parametrize('tz_str', DEFAULT_TZSTR_RULES_EQUIV_2003) def test_tzstr_default_end(tz_str): tzi = tz.tzstr(tz_str) dt_dst = datetime(2003, 10, 26, 0, 59, tzinfo=tzi) dt_dst_ambig = datetime(2003, 10, 26, 1, 00, tzinfo=tzi) dt_std_ambig = tz.enfold(dt_dst_ambig, fold=1) dt_std = datetime(2003, 10, 26, 2, 00, tzinfo=tzi) assert get_timezone_tuple(dt_dst) == EDT_TUPLE assert get_timezone_tuple(dt_dst_ambig) == EDT_TUPLE assert get_timezone_tuple(dt_std_ambig) == EST_TUPLE assert get_timezone_tuple(dt_std) == EST_TUPLE @pytest.mark.tzstr @pytest.mark.parametrize('tzstr_1', ['EST5EDT', 'EST5EDT4,M4.1.0/02:00:00,M10-5-0/02:00']) @pytest.mark.parametrize('tzstr_2', ['EST5EDT', 'EST5EDT4,M4.1.0/02:00:00,M10-5-0/02:00']) def test_tzstr_default_cmp(tzstr_1, tzstr_2): tz1 = tz.tzstr(tzstr_1) tz2 = tz.tzstr(tzstr_2) assert tz1 == tz2 class TZICalTest(unittest.TestCase, TzFoldMixin): def _gettz_str_tuple(self, tzname): TZ_EST = ( 'BEGIN:VTIMEZONE', 'TZID:US-Eastern', 'BEGIN:STANDARD', 'DTSTART:19971029T020000', 'RRULE:FREQ=YEARLY;BYDAY=+1SU;BYMONTH=11', 'TZOFFSETFROM:-0400', 'TZOFFSETTO:-0500', 'TZNAME:EST', 'END:STANDARD', 'BEGIN:DAYLIGHT', 'DTSTART:19980301T020000', 'RRULE:FREQ=YEARLY;BYDAY=+2SU;BYMONTH=03', 'TZOFFSETFROM:-0500', 'TZOFFSETTO:-0400', 'TZNAME:EDT', 'END:DAYLIGHT', 'END:VTIMEZONE' ) TZ_PST = ( 'BEGIN:VTIMEZONE', 'TZID:US-Pacific', 'BEGIN:STANDARD', 'DTSTART:19971029T020000', 'RRULE:FREQ=YEARLY;BYDAY=+1SU;BYMONTH=11', 'TZOFFSETFROM:-0700', 'TZOFFSETTO:-0800', 'TZNAME:PST', 'END:STANDARD', 'BEGIN:DAYLIGHT', 'DTSTART:19980301T020000', 'RRULE:FREQ=YEARLY;BYDAY=+2SU;BYMONTH=03', 'TZOFFSETFROM:-0800', 'TZOFFSETTO:-0700', 'TZNAME:PDT', 'END:DAYLIGHT', 'END:VTIMEZONE' ) TZ_AEST = ( 'BEGIN:VTIMEZONE', 'TZID:Australia-Sydney', 'BEGIN:STANDARD', 'DTSTART:19980301T030000', 'RRULE:FREQ=YEARLY;BYDAY=+1SU;BYMONTH=04', 'TZOFFSETFROM:+1100', 'TZOFFSETTO:+1000', 'TZNAME:AEST', 'END:STANDARD', 'BEGIN:DAYLIGHT', 'DTSTART:19971029T020000', 'RRULE:FREQ=YEARLY;BYDAY=+1SU;BYMONTH=10', 'TZOFFSETFROM:+1000', 'TZOFFSETTO:+1100', 'TZNAME:AEDT', 'END:DAYLIGHT', 'END:VTIMEZONE' ) TZ_LON = ( 'BEGIN:VTIMEZONE', 'TZID:Europe-London', 'BEGIN:STANDARD', 'DTSTART:19810301T030000', 'RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10;BYHOUR=02', 'TZOFFSETFROM:+0100', 'TZOFFSETTO:+0000', 'TZNAME:GMT', 'END:STANDARD', 'BEGIN:DAYLIGHT', 'DTSTART:19961001T030000', 'RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=03;BYHOUR=01', 'TZOFFSETFROM:+0000', 'TZOFFSETTO:+0100', 'TZNAME:BST', 'END:DAYLIGHT', 'END:VTIMEZONE' ) tzname_map = {'Australia/Sydney': TZ_AEST, 'America/Toronto': TZ_EST, 'America/New_York': TZ_EST, 'America/Los_Angeles': TZ_PST, 'Europe/London': TZ_LON} return tzname_map[tzname] def _gettz_str(self, tzname): return '\n'.join(self._gettz_str_tuple(tzname)) def _tzstr_dtstart_with_params(self, tzname, param_str): # Adds parameters to the DTSTART values of a given tzstr tz_str_tuple = self._gettz_str_tuple(tzname) out_tz = [] for line in tz_str_tuple: if line.startswith('DTSTART'): name, value = line.split(':', 1) line = name + ';' + param_str + ':' + value out_tz.append(line) return '\n'.join(out_tz) def gettz(self, tzname): tz_str = self._gettz_str(tzname) tzc = tz.tzical(StringIO(tz_str)).get() return tzc def testRepr(self): instr = StringIO(TZICAL_PST8PDT) instr.name = 'StringIO(PST8PDT)' tzc = tz.tzical(instr) self.assertEqual(repr(tzc), "tzical(" + repr(instr.name) + ")") # Test performance def _test_us_zone(self, tzc, func, values, start): if start: dt1 = datetime(2003, 3, 9, 1, 59) dt2 = datetime(2003, 3, 9, 2, 00) fold = [0, 0] else: dt1 = datetime(2003, 11, 2, 0, 59) dt2 = datetime(2003, 11, 2, 1, 00) fold = [0, 1] dts = (tz.enfold(dt.replace(tzinfo=tzc), fold=f) for dt, f in zip((dt1, dt2), fold)) for value, dt in zip(values, dts): self.assertEqual(func(dt), value) def _test_multi_zones(self, tzstrs, tzids, func, values, start): tzic = tz.tzical(StringIO('\n'.join(tzstrs))) for tzid, vals in zip(tzids, values): tzc = tzic.get(tzid) self._test_us_zone(tzc, func, vals, start) def _prepare_EST(self): tz_str = self._gettz_str('America/New_York') return tz.tzical(StringIO(tz_str)).get() def _testEST(self, start, test_type, tzc=None): if tzc is None: tzc = self._prepare_EST() argdict = { 'name': (datetime.tzname, ('EST', 'EDT')), 'offset': (datetime.utcoffset, (timedelta(hours=-5), timedelta(hours=-4))), 'dst': (datetime.dst, (timedelta(hours=0), timedelta(hours=1))) } func, values = argdict[test_type] if not start: values = reversed(values) self._test_us_zone(tzc, func, values, start=start) def testESTStartName(self): self._testEST(start=True, test_type='name') def testESTEndName(self): self._testEST(start=False, test_type='name') def testESTStartOffset(self): self._testEST(start=True, test_type='offset') def testESTEndOffset(self): self._testEST(start=False, test_type='offset') def testESTStartDST(self): self._testEST(start=True, test_type='dst') def testESTEndDST(self): self._testEST(start=False, test_type='dst') def testESTValueDatetime(self): # Violating one-test-per-test rule because we're not set up to do # parameterized tests and the manual proliferation is getting a bit # out of hand. tz_str = self._tzstr_dtstart_with_params('America/New_York', 'VALUE=DATE-TIME') tzc = tz.tzical(StringIO(tz_str)).get() for start in (True, False): for test_type in ('name', 'offset', 'dst'): self._testEST(start=start, test_type=test_type, tzc=tzc) def _testMultizone(self, start, test_type): tzstrs = (self._gettz_str('America/New_York'), self._gettz_str('America/Los_Angeles')) tzids = ('US-Eastern', 'US-Pacific') argdict = { 'name': (datetime.tzname, (('EST', 'EDT'), ('PST', 'PDT'))), 'offset': (datetime.utcoffset, ((timedelta(hours=-5), timedelta(hours=-4)), (timedelta(hours=-8), timedelta(hours=-7)))), 'dst': (datetime.dst, ((timedelta(hours=0), timedelta(hours=1)), (timedelta(hours=0), timedelta(hours=1)))) } func, values = argdict[test_type] if not start: values = map(reversed, values) self._test_multi_zones(tzstrs, tzids, func, values, start) def testMultiZoneStartName(self): self._testMultizone(start=True, test_type='name') def testMultiZoneEndName(self): self._testMultizone(start=False, test_type='name') def testMultiZoneStartOffset(self): self._testMultizone(start=True, test_type='offset') def testMultiZoneEndOffset(self): self._testMultizone(start=False, test_type='offset') def testMultiZoneStartDST(self): self._testMultizone(start=True, test_type='dst') def testMultiZoneEndDST(self): self._testMultizone(start=False, test_type='dst') def testMultiZoneKeys(self): est_str = self._gettz_str('America/New_York') pst_str = self._gettz_str('America/Los_Angeles') tzic = tz.tzical(StringIO('\n'.join((est_str, pst_str)))) # Sort keys because they are in a random order, being dictionary keys keys = sorted(tzic.keys()) self.assertEqual(keys, ['US-Eastern', 'US-Pacific']) # Test error conditions def testEmptyString(self): with self.assertRaises(ValueError): tz.tzical(StringIO("")) def testMultiZoneGet(self): tzic = tz.tzical(StringIO(TZICAL_EST5EDT + TZICAL_PST8PDT)) with self.assertRaises(ValueError): tzic.get() def testDtstartDate(self): tz_str = self._tzstr_dtstart_with_params('America/New_York', 'VALUE=DATE') with self.assertRaises(ValueError): tz.tzical(StringIO(tz_str)) def testDtstartTzid(self): tz_str = self._tzstr_dtstart_with_params('America/New_York', 'TZID=UTC') with self.assertRaises(ValueError): tz.tzical(StringIO(tz_str)) def testDtstartBadParam(self): tz_str = self._tzstr_dtstart_with_params('America/New_York', 'FOO=BAR') with self.assertRaises(ValueError): tz.tzical(StringIO(tz_str)) # Test Parsing def testGap(self): tzic = tz.tzical(StringIO('\n'.join((TZICAL_EST5EDT, TZICAL_PST8PDT)))) keys = sorted(tzic.keys()) self.assertEqual(keys, ['US-Eastern', 'US-Pacific']) @pytest.mark.parametrize( "offset", [ "+-500", "--500", "+ 500", "-05 0", "+\u0660\u0665\u0660\u0660", # Non-ASCII (Arabic-Indic) digits ], ) def test_tzical_offset_non_digit(offset): tz_str = TZICAL_EST5EDT.replace("TZOFFSETTO:-0500", "TZOFFSETTO:" + offset) with pytest.raises(ValueError): tz.tzical(StringIO(tz_str)) class TZTest(unittest.TestCase): def testFileStart1(self): tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertEqual(datetime(2003, 4, 6, 1, 59, tzinfo=tzc).tzname(), "EST") self.assertEqual( tz.enfold(datetime(2003, 4, 6, 2, 0, tzinfo=tzc), fold=0).tzname(), "EST", ) self.assertEqual( tz.enfold(datetime(2003, 4, 6, 2, 0, tzinfo=tzc), fold=1).tzname(), "EDT", ) self.assertEqual(datetime(2003, 4, 6, 3, 0, tzinfo=tzc).tzname(), "EDT") def testFileEnd1(self): tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertEqual( datetime(2003, 10, 26, 0, 59, tzinfo=tzc).tzname(), "EDT" ) end_est = tz.enfold(datetime(2003, 10, 26, 1, 0, tzinfo=tzc)) self.assertEqual(end_est.tzname(), "EST") def testFileLastTransition(self): # After the last transition, it goes to standard time in perpetuity tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertEqual(datetime(2037, 10, 25, 0, 59, tzinfo=tzc).tzname(), "EDT") last_date = tz.enfold(datetime(2037, 10, 25, 1, 0, tzinfo=tzc), fold=1) self.assertEqual(last_date.tzname(), "EST") self.assertEqual(datetime(2038, 5, 25, 12, 0, tzinfo=tzc).tzname(), "EST") def testInvalidFile(self): # Should throw a ValueError if an invalid file is passed with self.assertRaises(ValueError): tz.tzfile(BytesIO(b'BadFile')) def testFilestreamWithNameRepr(self): # If fileobj is a filestream with a "name" attribute this name should # be reflected in the tz object's repr fileobj = BytesIO(base64.b64decode(TZFILE_EST5EDT)) fileobj.name = 'foo' tzc = tz.tzfile(fileobj) self.assertEqual(repr(tzc), 'tzfile(' + repr('foo') + ')') def testLeapCountDecodesProperly(self): # This timezone has leapcnt, and failed to decode until # Eugene Oden notified about the issue. # As leap information is currently unused (and unstored) by tzfile() we # can only indirectly test this: Take advantage of tzfile() not closing # the input file if handed in as an opened file and assert that the # full file content has been read by tzfile(). Note: For this test to # work NEW_YORK must be in TZif version 1 format i.e. no more data # after TZif v1 header + data has been read fileobj = BytesIO(base64.b64decode(NEW_YORK)) tz.tzfile(fileobj) # we expect no remaining file content now, i.e. zero-length; if there's # still data we haven't read the file format correctly remaining_tzfile_content = fileobj.read() self.assertEqual(len(remaining_tzfile_content), 0) def testGMTHasNoDaylight(self): # tz.tzstr("GMT+2") improperly considered daylight saving time. # Issue reported by Lennart Regebro. dt = datetime(2007, 8, 6, 4, 10) self.assertEqual(tz.gettz("GMT+2").dst(dt), timedelta(0)) def testGMTOffset(self): # GMT and UTC offsets have inverted signal when compared to the # usual TZ variable handling. dt = datetime(2007, 8, 6, 4, 10, tzinfo=tz.UTC) self.assertEqual(dt.astimezone(tz=tz.tzstr("GMT+2")), datetime(2007, 8, 6, 6, 10, tzinfo=tz.tzstr("GMT+2"))) self.assertEqual(dt.astimezone(tz=tz.gettz("UTC-2")), datetime(2007, 8, 6, 2, 10, tzinfo=tz.tzstr("UTC-2"))) @unittest.skipIf(IS_WIN, "requires Unix") def testTZSetDoesntCorrupt(self): # if we start in non-UTC then tzset UTC make sure parse doesn't get # confused with TZEnvContext('UTC'): # this should parse to UTC timezone not the original timezone dt = parse('2014-07-20T12:34:56+00:00') self.assertEqual(str(dt), '2014-07-20 12:34:56+00:00') @pytest.mark.tzfile def test_tzfile_sub_minute_offset(): tzc = tz.tzfile(BytesIO(base64.b64decode(EUROPE_HELSINKI))) offset = timedelta(hours=1, minutes=39, seconds=52) assert datetime(1900, 1, 1, 0, 0, tzinfo=tzc).utcoffset() == offset @pytest.mark.tzfile def test_samoa_transition(tz_source): # utcoffset() was erroneously returning +14:00 an hour early (GH #812) APIA = tz.gettz('Pacific/Apia') assert APIA is not None dt = datetime(2011, 12, 29, 23, 59, tzinfo=APIA) assert dt.utcoffset() == timedelta(hours=-10) # Make sure the transition actually works, too dt_after = (dt.astimezone(tz.UTC) + timedelta(minutes=1)).astimezone(APIA) assert dt_after == datetime(2011, 12, 31, tzinfo=APIA) assert dt_after.utcoffset() == timedelta(hours=14) @unittest.skipUnless(IS_WIN, "Requires Windows") class TzWinTest(unittest.TestCase, TzWinFoldMixin): def setUp(self): self.tzclass = tzwin.tzwin def testTzResLoadName(self): # This may not work right on non-US locales. tzr = tzwin.tzres() self.assertEqual(tzr.load_name(112), "Eastern Standard Time") def testTzResNameFromString(self): tzr = tzwin.tzres() self.assertEqual(tzr.name_from_string('@tzres.dll,-221'), 'Alaskan Daylight Time') self.assertEqual(tzr.name_from_string('Samoa Daylight Time'), 'Samoa Daylight Time') with self.assertRaises(ValueError): tzr.name_from_string('@tzres.dll,100') def testIsdstZoneWithNoDaylightSaving(self): tz = tzwin.tzwin("UTC") dt = parse("2013-03-06 19:08:15") self.assertFalse(tz._isdst(dt)) def testOffset(self): tz = tzwin.tzwin("Cape Verde Standard Time") self.assertEqual(tz.utcoffset(datetime(1995, 5, 21, 12, 9, 13)), timedelta(-1, 82800)) def testTzwinName(self): # https://github.com/dateutil/dateutil/issues/143 tw = tz.tzwin('Eastern Standard Time') # Cover the transitions for at least two years. ESTs = 'Eastern Standard Time' EDTs = 'Eastern Daylight Time' transition_dates = [(datetime(2015, 3, 8, 0, 59), ESTs), (datetime(2015, 3, 8, 3, 1), EDTs), (datetime(2015, 11, 1, 0, 59), EDTs), (datetime(2015, 11, 1, 3, 1), ESTs), (datetime(2016, 3, 13, 0, 59), ESTs), (datetime(2016, 3, 13, 3, 1), EDTs), (datetime(2016, 11, 6, 0, 59), EDTs), (datetime(2016, 11, 6, 3, 1), ESTs)] for t_date, expected in transition_dates: self.assertEqual(t_date.replace(tzinfo=tw).tzname(), expected) def testTzwinRepr(self): tw = tz.tzwin('Yakutsk Standard Time') self.assertEqual(repr(tw), 'tzwin(' + repr('Yakutsk Standard Time') + ')') def testTzWinEquality(self): # https://github.com/dateutil/dateutil/issues/151 tzwin_names = ('Eastern Standard Time', 'West Pacific Standard Time', 'Yakutsk Standard Time', 'Iran Standard Time', 'UTC') for tzwin_name in tzwin_names: # Get two different instances to compare tw1 = tz.tzwin(tzwin_name) tw2 = tz.tzwin(tzwin_name) self.assertEqual(tw1, tw2) def testTzWinInequality(self): # https://github.com/dateutil/dateutil/issues/151 # Note these last two currently differ only in their name. tzwin_names = (('Eastern Standard Time', 'Yakutsk Standard Time'), ('Greenwich Standard Time', 'GMT Standard Time'), ('GMT Standard Time', 'UTC'), ('E. South America Standard Time', 'Argentina Standard Time')) for tzwn1, tzwn2 in tzwin_names: # Get two different instances to compare tw1 = tz.tzwin(tzwn1) tw2 = tz.tzwin(tzwn2) self.assertNotEqual(tw1, tw2) def testTzWinEqualityInvalid(self): # Compare to objects that do not implement comparison with this # (should default to False) UTC = tz.UTC EST = tz.tzwin('Eastern Standard Time') self.assertFalse(EST == UTC) self.assertFalse(EST == 1) self.assertFalse(UTC == EST) self.assertTrue(EST != UTC) self.assertTrue(EST != 1) def testTzWinInequalityUnsupported(self): # Compare it to an object that is promiscuous about equality, but for # which tzwin does not implement an equality operator. EST = tz.tzwin('Eastern Standard Time') self.assertTrue(EST == ComparesEqual) self.assertFalse(EST != ComparesEqual) def testTzwinTimeOnlyDST(self): # For zones with DST, .dst() should return None tw_est = tz.tzwin('Eastern Standard Time') self.assertIs(dt_time(14, 10, tzinfo=tw_est).dst(), None) # This zone has no DST, so .dst() can return 0 tw_sast = tz.tzwin('South Africa Standard Time') self.assertEqual(dt_time(14, 10, tzinfo=tw_sast).dst(), timedelta(0)) def testTzwinTimeOnlyUTCOffset(self): # For zones with DST, .utcoffset() should return None tw_est = tz.tzwin('Eastern Standard Time') self.assertIs(dt_time(14, 10, tzinfo=tw_est).utcoffset(), None) # This zone has no DST, so .utcoffset() returns standard offset tw_sast = tz.tzwin('South Africa Standard Time') self.assertEqual(dt_time(14, 10, tzinfo=tw_sast).utcoffset(), timedelta(hours=2)) def testTzwinTimeOnlyTZName(self): # For zones with DST, the name defaults to standard time tw_est = tz.tzwin('Eastern Standard Time') self.assertEqual(dt_time(14, 10, tzinfo=tw_est).tzname(), 'Eastern Standard Time') # For zones with no DST, this should work normally. tw_sast = tz.tzwin('South Africa Standard Time') self.assertEqual(dt_time(14, 10, tzinfo=tw_sast).tzname(), 'South Africa Standard Time') @unittest.skipUnless(IS_WIN, "Requires Windows") class TzWinLocalTest(unittest.TestCase, TzWinFoldMixin): def setUp(self): self.tzclass = tzwin.tzwinlocal self.context = TZWinContext def get_args(self, tzname): return () def testLocal(self): # Not sure how to pin a local time zone, so for now we're just going # to run this and make sure it doesn't raise an error # See GitHub Issue #135: https://github.com/dateutil/dateutil/issues/135 datetime.now(tzwin.tzwinlocal()) def testTzwinLocalUTCOffset(self): with TZWinContext('Eastern Standard Time'): tzwl = tzwin.tzwinlocal() self.assertEqual(datetime(2014, 3, 11, tzinfo=tzwl).utcoffset(), timedelta(hours=-4)) def testTzwinLocalName(self): # https://github.com/dateutil/dateutil/issues/143 ESTs = 'Eastern Standard Time' EDTs = 'Eastern Daylight Time' transition_dates = [(datetime(2015, 3, 8, 0, 59), ESTs), (datetime(2015, 3, 8, 3, 1), EDTs), (datetime(2015, 11, 1, 0, 59), EDTs), (datetime(2015, 11, 1, 3, 1), ESTs), (datetime(2016, 3, 13, 0, 59), ESTs), (datetime(2016, 3, 13, 3, 1), EDTs), (datetime(2016, 11, 6, 0, 59), EDTs), (datetime(2016, 11, 6, 3, 1), ESTs)] with TZWinContext('Eastern Standard Time'): tw = tz.tzwinlocal() for t_date, expected in transition_dates: self.assertEqual(t_date.replace(tzinfo=tw).tzname(), expected) def testTzWinLocalRepr(self): tw = tz.tzwinlocal() self.assertEqual(repr(tw), 'tzwinlocal()') def testTzwinLocalRepr(self): # https://github.com/dateutil/dateutil/issues/143 with TZWinContext('Eastern Standard Time'): tw = tz.tzwinlocal() self.assertEqual(str(tw), 'tzwinlocal(' + repr('Eastern Standard Time') + ')') with TZWinContext('Pacific Standard Time'): tw = tz.tzwinlocal() self.assertEqual(str(tw), 'tzwinlocal(' + repr('Pacific Standard Time') + ')') def testTzwinLocalEquality(self): tw_est = tz.tzwin('Eastern Standard Time') tw_pst = tz.tzwin('Pacific Standard Time') with TZWinContext('Eastern Standard Time'): twl1 = tz.tzwinlocal() twl2 = tz.tzwinlocal() self.assertEqual(twl1, twl2) self.assertEqual(twl1, tw_est) self.assertNotEqual(twl1, tw_pst) with TZWinContext('Pacific Standard Time'): twl1 = tz.tzwinlocal() twl2 = tz.tzwinlocal() tw = tz.tzwin('Pacific Standard Time') self.assertEqual(twl1, twl2) self.assertEqual(twl1, tw) self.assertEqual(twl1, tw_pst) self.assertNotEqual(twl1, tw_est) def testTzwinLocalTimeOnlyDST(self): # For zones with DST, .dst() should return None with TZWinContext('Eastern Standard Time'): twl = tz.tzwinlocal() self.assertIs(dt_time(14, 10, tzinfo=twl).dst(), None) # This zone has no DST, so .dst() can return 0 with TZWinContext('South Africa Standard Time'): twl = tz.tzwinlocal() self.assertEqual(dt_time(14, 10, tzinfo=twl).dst(), timedelta(0)) def testTzwinLocalTimeOnlyUTCOffset(self): # For zones with DST, .utcoffset() should return None with TZWinContext('Eastern Standard Time'): twl = tz.tzwinlocal() self.assertIs(dt_time(14, 10, tzinfo=twl).utcoffset(), None) # This zone has no DST, so .utcoffset() returns standard offset with TZWinContext('South Africa Standard Time'): twl = tz.tzwinlocal() self.assertEqual(dt_time(14, 10, tzinfo=twl).utcoffset(), timedelta(hours=2)) def testTzwinLocalTimeOnlyTZName(self): # For zones with DST, the name defaults to standard time with TZWinContext('Eastern Standard Time'): twl = tz.tzwinlocal() self.assertEqual(dt_time(14, 10, tzinfo=twl).tzname(), 'Eastern Standard Time') # For zones with no DST, this should work normally. with TZWinContext('South Africa Standard Time'): twl = tz.tzwinlocal() self.assertEqual(dt_time(14, 10, tzinfo=twl).tzname(), 'South Africa Standard Time') class TzPickleTest(PicklableMixin, unittest.TestCase): _asfile = False def setUp(self): self.assertPicklable = partial(self.assertPicklable, asfile=self._asfile) def testPickleTzUTC(self): self.assertPicklable(tz.tzutc(), singleton=True) def testPickleTzOffsetZero(self): self.assertPicklable(tz.tzoffset('UTC', 0), singleton=True) def testPickleTzOffsetPos(self): self.assertPicklable(tz.tzoffset('UTC+1', 3600), singleton=True) def testPickleTzOffsetNeg(self): self.assertPicklable(tz.tzoffset('UTC-1', -3600), singleton=True) @pytest.mark.tzlocal def testPickleTzLocal(self): self.assertPicklable(tz.tzlocal()) def testPickleTzFileEST5EDT(self): tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertPicklable(tzc) def testPickleTzFileEurope_Helsinki(self): tzc = tz.tzfile(BytesIO(base64.b64decode(EUROPE_HELSINKI))) self.assertPicklable(tzc) def testPickleTzFileNew_York(self): tzc = tz.tzfile(BytesIO(base64.b64decode(NEW_YORK))) self.assertPicklable(tzc) @unittest.skip("Known failure") def testPickleTzICal(self): tzc = tz.tzical(StringIO(TZICAL_EST5EDT)).get() self.assertPicklable(tzc) @requires_tzdata def testPickleZoneFileGettz(self): zoneinfo_file = zoneinfo.get_zonefile_instance() tzi = zoneinfo_file.get('America/New_York') self.assertIsNot(tzi, None) self.assertPicklable(tzi) class TzPickleFileTest(TzPickleTest): """ Run all the TzPickleTest tests, using a temporary file """ _asfile = True @pytest.mark.parametrize("asfile", [False, True]) def test_pickle_gettz(tz_source, asfile): zone = tz.gettz("America/New_York") assert zone is not None if asfile: with tempfile.TemporaryFile("w+b") as f: pickle.dump(zone, f) f.seek(0) unpickled = pickle.load(f) else: unpickled = pickle.loads(pickle.dumps(zone)) assert unpickled is not zone assert unpickled == zone class DatetimeAmbiguousTest(TzSourceMixin, unittest.TestCase): """ Test the datetime_exists / datetime_ambiguous functions """ def testNoTzSpecified(self): with self.assertRaises(ValueError): tz.datetime_ambiguous(datetime(2016, 4, 1, 2, 9)) def _get_no_support_tzinfo_class(self, dt_start, dt_end, dst_only=False): # Generates a class of tzinfo with no support for is_ambiguous # where dates between dt_start and dt_end are ambiguous. class FoldingTzInfo(tzinfo): def utcoffset(self, dt): if not dst_only: dt_n = dt.replace(tzinfo=None) if dt_start <= dt_n < dt_end and dt_n.fold: return timedelta(hours=-1) return timedelta(hours=0) def dst(self, dt): dt_n = dt.replace(tzinfo=None) if dt_start <= dt_n < dt_end and dt_n.fold: return timedelta(hours=1) else: return timedelta(0) return FoldingTzInfo def _get_no_support_tzinfo(self, dt_start, dt_end, dst_only=False): return self._get_no_support_tzinfo_class(dt_start, dt_end, dst_only)() def testNoSupportAmbiguityFoldNaive(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_no_support_tzinfo(dt_start, dt_end) self.assertTrue(tz.datetime_ambiguous(datetime(2018, 9, 1, 1, 30), tz=tzi)) def testNoSupportAmbiguityFoldAware(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_no_support_tzinfo(dt_start, dt_end) self.assertTrue(tz.datetime_ambiguous(datetime(2018, 9, 1, 1, 30, tzinfo=tzi))) def testNoSupportAmbiguityUnambiguousNaive(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_no_support_tzinfo(dt_start, dt_end) self.assertFalse(tz.datetime_ambiguous(datetime(2018, 10, 1, 12, 30), tz=tzi)) def testNoSupportAmbiguityUnambiguousAware(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_no_support_tzinfo(dt_start, dt_end) self.assertFalse(tz.datetime_ambiguous(datetime(2018, 10, 1, 12, 30, tzinfo=tzi))) def testNoSupportAmbiguityFoldDSTOnly(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_no_support_tzinfo(dt_start, dt_end, dst_only=True) self.assertTrue(tz.datetime_ambiguous(datetime(2018, 9, 1, 1, 30), tz=tzi)) def testNoSupportAmbiguityUnambiguousDSTOnly(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_no_support_tzinfo(dt_start, dt_end, dst_only=True) self.assertFalse(tz.datetime_ambiguous(datetime(2018, 10, 1, 12, 30), tz=tzi)) def testSupportAmbiguityFoldNaive(self): tzi = tz.gettz("America/New_York") dt = datetime(2011, 11, 6, 1, 30) self.assertTrue(tz.datetime_ambiguous(dt, tz=tzi)) def testSupportAmbiguityFoldAware(self): tzi = tz.gettz("America/New_York") dt = datetime(2011, 11, 6, 1, 30, tzinfo=tzi) self.assertTrue(tz.datetime_ambiguous(dt)) def testSupportAmbiguityUnambiguousAware(self): tzi = tz.gettz("America/New_York") dt = datetime(2011, 11, 6, 4, 30) self.assertFalse(tz.datetime_ambiguous(dt, tz=tzi)) def testSupportAmbiguityUnambiguousNaive(self): tzi = tz.gettz("America/New_York") dt = datetime(2011, 11, 6, 4, 30, tzinfo=tzi) self.assertFalse(tz.datetime_ambiguous(dt)) def _get_ambig_error_tzinfo(self, dt_start, dt_end, dst_only=False): cTzInfo = self._get_no_support_tzinfo_class(dt_start, dt_end, dst_only) # Takes the wrong number of arguments and raises an error anyway. class FoldTzInfoRaises(cTzInfo): def is_ambiguous(self, dt, other_arg): raise NotImplementedError('This is not implemented') return FoldTzInfoRaises() def testIncompatibleAmbiguityFoldNaive(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_ambig_error_tzinfo(dt_start, dt_end) self.assertTrue(tz.datetime_ambiguous(datetime(2018, 9, 1, 1, 30), tz=tzi)) def testIncompatibleAmbiguityFoldAware(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_ambig_error_tzinfo(dt_start, dt_end) self.assertTrue(tz.datetime_ambiguous(datetime(2018, 9, 1, 1, 30, tzinfo=tzi))) def testIncompatibleAmbiguityUnambiguousNaive(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_ambig_error_tzinfo(dt_start, dt_end) self.assertFalse(tz.datetime_ambiguous(datetime(2018, 10, 1, 12, 30), tz=tzi)) def testIncompatibleAmbiguityUnambiguousAware(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_ambig_error_tzinfo(dt_start, dt_end) self.assertFalse(tz.datetime_ambiguous(datetime(2018, 10, 1, 12, 30, tzinfo=tzi))) def testIncompatibleAmbiguityFoldDSTOnly(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_ambig_error_tzinfo(dt_start, dt_end, dst_only=True) self.assertTrue(tz.datetime_ambiguous(datetime(2018, 9, 1, 1, 30), tz=tzi)) def testIncompatibleAmbiguityUnambiguousDSTOnly(self): dt_start = datetime(2018, 9, 1, 1, 0) dt_end = datetime(2018, 9, 1, 2, 0) tzi = self._get_ambig_error_tzinfo(dt_start, dt_end, dst_only=True) self.assertFalse(tz.datetime_ambiguous(datetime(2018, 10, 1, 12, 30), tz=tzi)) def testSpecifiedTzOverridesAttached(self): # If a tz is specified, the datetime will be treated as naive. # This is not ambiguous in the local zone dt = datetime(2011, 11, 6, 1, 30, tzinfo=tz.gettz('Australia/Sydney')) self.assertFalse(tz.datetime_ambiguous(dt)) tzi = tz.gettz("America/New_York") self.assertTrue(tz.datetime_ambiguous(dt, tz=tzi)) class DatetimeAmbiguousTzdataTest(DatetimeAmbiguousTest): tz_source = "tzdata" class DatetimeExistsTest(TzSourceMixin, unittest.TestCase): def testNoTzSpecified(self): with self.assertRaises(ValueError): tz.datetime_exists(datetime(2016, 4, 1, 2, 9)) def testInGapNaive(self): tzi = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 2, 30) self.assertFalse(tz.datetime_exists(dt, tz=tzi)) def testInGapAware(self): tzi = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 2, 30, tzinfo=tzi) self.assertFalse(tz.datetime_exists(dt)) def testExistsNaive(self): tzi = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 10, 30) self.assertTrue(tz.datetime_exists(dt, tz=tzi)) def testExistsAware(self): tzi = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 10, 30, tzinfo=tzi) self.assertTrue(tz.datetime_exists(dt)) def testSpecifiedTzOverridesAttached(self): EST = tz.gettz("America/New_York") AEST = tz.gettz("Australia/Sydney") dt = datetime(2012, 10, 7, 2, 30, tzinfo=EST) # This time exists self.assertFalse(tz.datetime_exists(dt, tz=AEST)) class DatetimeExistsTzdataTest(DatetimeExistsTest): tz_source = "tzdata" class TestEnfold: def test_enter_fold_default(self): dt = tz.enfold(datetime(2020, 1, 19, 3, 32)) assert dt.fold == 1 def test_enter_fold(self): dt = tz.enfold(datetime(2020, 1, 19, 3, 32), fold=1) assert dt.fold == 1 def test_exit_fold(self): dt = tz.enfold(datetime(2020, 1, 19, 3, 32), fold=0) assert dt.fold == 0 def test_defold(self): dt = tz.enfold(datetime(2020, 1, 19, 3, 32), fold=1) dt2 = tz.enfold(dt, fold=0) assert dt2.fold == 0 @pytest.mark.tz_resolve_imaginary class ImaginaryDateTest(TzSourceMixin, unittest.TestCase): def testSydneyForward(self): tzi = tz.gettz("Australia/Sydney") dt = datetime(2018, 10, 7, 2, 30, tzinfo=tzi) dt_act = tz.resolve_imaginary(dt) dt_exp = datetime(2018, 10, 7, 3, 30, tzinfo=tzi) self.assertEqual(dt_act, dt_exp) def testLondonForward(self): tzi = tz.gettz('Europe/London') dt = datetime(2018, 3, 25, 1, 30, tzinfo=tzi) dt_act = tz.resolve_imaginary(dt) dt_exp = datetime(2018, 3, 25, 2, 30, tzinfo=tzi) self.assertEqual(dt_act, dt_exp) def testKyivForward(self): tzi = tz.gettz("Europe/Kyiv") dt = datetime(2018, 3, 25, 3, 30, tzinfo=tzi) dt_act = tz.resolve_imaginary(dt) dt_exp = datetime(2018, 3, 25, 4, 30, tzinfo=tzi) self.assertEqual(dt_act, dt_exp) class ImaginaryDateTzdataTest(ImaginaryDateTest): tz_source = "tzdata" def _gettz(key): # A key missing from the data should fail the test, not pass it with a # naive datetime. zone = tz.gettz(key) assert zone is not None, key return zone @pytest.mark.tz_resolve_imaginary @pytest.mark.parametrize( "key, dt", [ ("America/New_York", datetime(2017, 11, 5, 1, 30)), ("Europe/London", datetime(2018, 10, 28, 1, 30)), ("Australia/Sydney", datetime(2017, 4, 2, 2, 30)), ], ) def test_resolve_imaginary_ambiguous(tz_source, key, dt): dt = dt.replace(tzinfo=_gettz(key)) assert tz.resolve_imaginary(dt) is dt dt_f = tz.enfold(dt) assert dt is not dt_f assert tz.resolve_imaginary(dt_f) is dt_f @pytest.mark.tz_resolve_imaginary @pytest.mark.parametrize( "key, dt", [ ("America/New_York", datetime(2017, 6, 2, 12, 30)), ("Europe/London", datetime(2018, 4, 2, 9, 30)), ("Australia/Sydney", datetime(2017, 2, 2, 16, 30)), ("America/New_York", datetime(2017, 12, 2, 12, 30)), ("Europe/London", datetime(2018, 12, 2, 9, 30)), ("Australia/Sydney", datetime(2017, 6, 2, 16, 30)), ], ) def test_resolve_imaginary_existing(tz_source, key, dt): dt = dt.replace(tzinfo=_gettz(key)) assert tz.resolve_imaginary(dt) is dt @pytest.mark.tz_resolve_imaginary @pytest.mark.parametrize('dt', [ datetime(2025, 9, 25, 1, 17, tzinfo=tz.UTC), datetime(2025, 9, 25, 1, 17, tzinfo=tz.tzoffset('EST', -18000)), datetime(2019, 3, 4, tzinfo=None) ]) def test_resolve_imaginary_existing_fixed(dt): assert tz.resolve_imaginary(dt) is dt resolve_imaginary_tests = [ ( "Europe/London", datetime(2018, 3, 25, 1, 30), datetime(2018, 3, 25, 2, 30), ), ( "America/New_York", datetime(2017, 3, 12, 2, 30), datetime(2017, 3, 12, 3, 30), ), ( "Australia/Sydney", datetime(2014, 10, 5, 2, 0), datetime(2014, 10, 5, 3, 0), ), # Kiritimati skipped 1994-12-31 when it moved across the date line. Data # older than 2018d had the skipped day wrong. ( "Pacific/Kiritimati", datetime(1994, 12, 31, 12, 30), datetime(1995, 1, 1, 12, 30), ), ] resolve_imaginary_tests.append( ( "Africa/Monrovia", datetime(1972, 1, 7, 0, 30), datetime(1972, 1, 7, 1, 14, 30), ) ) @pytest.mark.tz_resolve_imaginary @pytest.mark.parametrize("key, dt, dt_exp", resolve_imaginary_tests) def test_resolve_imaginary(tz_source, key, dt, dt_exp): tzi = _gettz(key) dt = dt.replace(tzinfo=tzi) dt_exp = dt_exp.replace(tzinfo=tzi) dt_r = tz.resolve_imaginary(dt) assert dt_r == dt_exp assert dt_r.tzname() == dt_exp.tzname() assert dt_r.utcoffset() == dt_exp.utcoffset() python_dateutil-4.0.0/tests/test_tzfile.py0000644000000000000000000027431013615410400015726 0ustar00"""Tests for `tz.tzfile`.""" import base64 import functools import gzip import io import json import os import pickle import shutil import struct import sys import tempfile import threading import time as time_module import warnings from datetime import date, datetime, time, timedelta import attr import pytest from dateutil import tz from ._common import set_tzpath IS_WIN = sys.platform.startswith("win") MIN_DT_V1 = datetime(1970, 1, 1) - timedelta(seconds=2**31) MAX_DT_V1 = datetime(1970, 1, 1) + timedelta(seconds=2**31) #### # Test utilities def _copy_resource_to(resource, path): """Copies a test resource to a path on disk.""" from dateutil._tzdata_impl import _open_binary parent_dir = os.path.dirname(path) if not os.path.exists(parent_dir): os.makedirs(parent_dir) with _open_binary("tests.resources", resource) as f: with open(path, "wb") as out_f: out_f.write(f.read()) @pytest.fixture def transition(request, tzpath_zoneinfo_cache): key, dt, fold, offset = request.param if dt.tzinfo is not None: dt_n = dt.astimezone(tz.UTC).replace(tzinfo=None) else: dt_n = dt if tzpath_zoneinfo_cache == "v1" and not (MIN_DT_V1 <= dt_n <= MAX_DT_V1): pytest.skip( "Out of range for V1 files" ) # TODO: Avoid generating these tests at all yield ExpectedTransition(key=key, dt=dt, fold=fold, offset=offset) @pytest.fixture(scope="module") def zoneinfo_cache(request): """ A fixture that extracts TZif files from a JSON file mapping timezone names to base64-encoded gzipped TZif data. The files are extracted into a temporary directory once per module and deleted afterwards. Returns: tuple: The path to the directory containing the extracted timezone files, and the name of the data set. """ input_file = os.path.join( os.path.dirname(__file__), "resources", "data", "zoneinfo_%s.json" % request.param, ) cache_dir = tempfile.mkdtemp(prefix="zoneinfo_%s_" % request.param) try: extract_tzif_files(input_file, cache_dir) yield os.path.abspath(cache_dir), request.param finally: shutil.rmtree(cache_dir) def extract_tzif_files(input_file, cache_dir): """ Extract TZif files from a JSON file and save them to the cache directory. Args: input_file: Path to the JSON file containing the TZif data. cache_dir: Path to the directory where the extracted files will be stored. """ try: with open(input_file, "r") as f: timezone_data = json.load(f) for timezone_name, encoded_data in timezone_data.items(): # Create the directory structure for the timezone timezone_path = os.path.join(cache_dir, timezone_name) os.makedirs(os.path.dirname(timezone_path), exist_ok=True) # Decode and decompress the TZif data compressed_data = base64.b64decode(encoded_data) tzif_data = gzip.decompress(compressed_data) # Write the TZif file with open(timezone_path, "wb") as f: f.write(tzif_data) except (json.JSONDecodeError, OSError) as e: raise RuntimeError( "Failed to extract TZif files from {input_file}: {e}".format( input_file=input_file, e=e ) ) def construct_zone( transitions, after=None, version=3, leap_seconds=(), indicators=False ): """Builds a TZif file. ``leap_seconds`` is a sequence of ``(timestamp, correction)`` pairs, and ``indicators`` adds standard/wall and UT/local indicators for every local time type. Neither affects what the file means to ``tzfile``, which skips over them, but they change the layout of the file. """ offset_lists = [[], []] trans_times_lists = [[], []] trans_idx_lists = [[], []] v1_range = (-(2**31), 2**31) v2_range = (-(2**63), 2**63) ranges = [v1_range, v2_range] def zt_as_tuple(zt): # zt may be a tuple (timestamp, offset_before, offset_after) or # a ZoneTransition object -- this is to allow the timestamp to be # values that are outside the valid range for datetimes but still # valid 64-bit timestamps. if isinstance(zt, tuple): return zt if zt.transition: trans_time = int(datetime.timestamp(zt.transition_utc)) else: trans_time = None return (trans_time, zt.offset_before, zt.offset_after) transitions = sorted(map(zt_as_tuple, transitions), key=lambda x: x[0]) for zt in transitions: trans_time, offset_before, offset_after = zt for v, (dt_min, dt_max) in enumerate(ranges): offsets = offset_lists[v] trans_times = trans_times_lists[v] trans_idx = trans_idx_lists[v] if trans_time is not None and not (dt_min <= trans_time <= dt_max): continue if offset_before not in offsets: offsets.append(offset_before) if offset_after not in offsets: offsets.append(offset_after) if trans_time is not None: trans_times.append(trans_time) trans_idx.append(offsets.index(offset_after)) zonefile = io.BytesIO() time_types = ("l", "q") for v in range(min((version, 2))): offsets = offset_lists[v] trans_times = trans_times_lists[v] trans_idx = trans_idx_lists[v] time_type = time_types[v] # Translate the offsets into something closer to the C values abbrstr = bytearray() ttinfos = [] for offset in offsets: utcoff = int(offset.utcoffset.total_seconds()) isdst = bool(offset.dst) abbrind = len(abbrstr) ttinfos.append((utcoff, isdst, abbrind)) abbrstr += offset.tzname.encode("ascii") + b"\x00" abbrstr = bytes(abbrstr) typecnt = len(offsets) timecnt = len(trans_times) charcnt = len(abbrstr) dt_min, dt_max = ranges[v] leaps = [ (trans_time, correction) for trans_time, correction in leap_seconds if dt_min <= trans_time <= dt_max ] leapcnt = len(leaps) isstd = isutc = [0] * typecnt if indicators else [] isstdcnt = len(isstd) isutcnt = len(isutc) # Write the header zonefile.write(b"TZif") # Version 1 files have a NUL byte in place of the version number if version == 1: zonefile.write(b"\x00") else: zonefile.write(("%d" % version).encode("ascii")) zonefile.write(b"\x00" * 15) # Reserved zonefile.write( struct.pack( ">6l", isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt ) ) # Now the transition data zonefile.write( struct.pack( ">{timecnt}{time_type}".format( timecnt=timecnt, time_type=time_type ), *trans_times ) ) zonefile.write( struct.pack(">{timecnt}B".format(timecnt=timecnt), *trans_idx) ) for ttinfo in ttinfos: zonefile.write(struct.pack(">lbb", *ttinfo)) zonefile.write(bytes(abbrstr)) # Now the leap second records and the indicators, in that order for leap in leaps: zonefile.write(struct.pack(">%sl" % time_type, *leap)) zonefile.write( struct.pack("{isstdcnt}b".format(isstdcnt=isstdcnt), *isstd) ) zonefile.write( struct.pack("{isutcnt}b".format(isutcnt=isutcnt), *isutc) ) # Finally we write the TZ string if we're writing a Version 2+ file if v > 0: zonefile.write(b"\x0a") if after is None: after = "" zonefile.write(after.encode("ascii")) zonefile.write(b"\x0a") zonefile.seek(0) return zonefile @functools.cache def _tzstr_header(): out = bytearray() # The TZif format always starts with a Version 1 file followed by # the Version 2+ file. In this case, we have no transitions, just # the tzstr in the footer, so up to the footer, the files are # identical and we can just write the same file twice in a row. for _ in range(2): out += b"TZif" # Magic value out += b"3" # Version out += b" " * 15 # Reserved # We will not write any of the manual transition parts out += struct.pack(">6l", 0, 0, 0, 0, 0, 0) return bytes(out) def zone_from_tzstr(tzstr, encoding="ascii"): """Creates a zoneinfo file following a POSIX rule.""" zonefile = io.BytesIO(_tzstr_header()) zonefile.seek(0, 2) # Write the footer zonefile.write(b"\x0a") zonefile.write(tzstr.encode(encoding)) zonefile.write(b"\x0a") zonefile.seek(0) return tz.tzfile(zonefile, key=tzstr) @pytest.fixture def tzpath_zoneinfo_cache(zoneinfo_cache): # Parameterize this indirectly by parameterizing zoneinfo_cache with set_tzpath((zoneinfo_cache[0],), block_tzdata=True): yield zoneinfo_cache[1] def as_list(f): @functools.wraps(f) def inner_func(*args, **kwargs): return list(f(*args, **kwargs)) return inner_func #### # Classes representing test data ZERO = timedelta(0) ONE_H = timedelta(hours=1) SECOND = timedelta(seconds=1) @attr.s class ZoneOffset: tzname = attr.ib() utcoffset = attr.ib() dst = attr.ib(default=ZERO) @attr.s class ZoneTransition: transition = attr.ib() offset_before = attr.ib() offset_after = attr.ib() marks = attr.ib(default=None) @property def transition_utc(self): return (self.transition - self.offset_before.utcoffset).replace( tzinfo=tz.UTC ) @property def wall_transition(self): """The local transition time using the (possibly rounded) offsets Identical to ``self.transition`` when sub-minute offsets are supported. """ return ( self.transition_utc.replace(tzinfo=None) + self.offset_before.utcoffset ) @property def fold(self): """Whether this introduces a fold""" return self.offset_before.utcoffset > self.offset_after.utcoffset @property def gap(self): """Whether this introduces a gap""" return self.offset_before.utcoffset < self.offset_after.utcoffset @property def delta(self): return self.offset_after.utcoffset - self.offset_before.utcoffset @property def anomaly_start(self): if self.fold: return self.wall_transition + self.delta else: return self.wall_transition @property def anomaly_end(self): if not self.fold: return self.wall_transition + self.delta else: return self.wall_transition @attr.frozen class ExpectedTransition: key = attr.ib() dt = attr.ib() fold = attr.ib() offset = attr.ib() #### # Test data @functools.cache def get_zonedump_data(): def _zone_dump_data(): def _Africa_Abidjan(): LMT = ZoneOffset("LMT", timedelta(seconds=-968)) GMT = ZoneOffset("GMT", ZERO) return [ ZoneTransition(datetime(1912, 1, 1), LMT, GMT), ] def _Africa_Casablanca(): P00_s = ZoneOffset("+00", ZERO, ZERO) P01_d = ZoneOffset("+01", ONE_H, ONE_H) P00_d = ZoneOffset("+00", ZERO, -ONE_H) P01_s = ZoneOffset("+01", ONE_H, ZERO) return [ # Morocco sometimes pauses DST during Ramadan ZoneTransition(datetime(2018, 3, 25, 2), P00_s, P01_d), ZoneTransition(datetime(2018, 5, 13, 3), P01_d, P00_s), ZoneTransition(datetime(2018, 6, 17, 2), P00_s, P01_d), # On October 28th Morocco set standard time to +01, # with negative DST only during Ramadan ZoneTransition(datetime(2018, 10, 28, 3), P01_d, P01_s), ZoneTransition(datetime(2019, 5, 5, 3), P01_s, P00_d), ZoneTransition(datetime(2019, 6, 9, 2), P00_d, P01_s), ] def _America_Los_Angeles(): LMT = ZoneOffset("LMT", timedelta(seconds=-28378), ZERO) PST = ZoneOffset("PST", timedelta(hours=-8), ZERO) PDT = ZoneOffset("PDT", timedelta(hours=-7), ONE_H) PWT = ZoneOffset("PWT", timedelta(hours=-7), ONE_H) PPT = ZoneOffset("PPT", timedelta(hours=-7), ONE_H) return [ ZoneTransition(datetime(1883, 11, 18, 12, 7, 2), LMT, PST), ZoneTransition(datetime(1918, 3, 31, 2), PST, PDT), ZoneTransition(datetime(1918, 3, 31, 2), PST, PDT), ZoneTransition(datetime(1918, 10, 27, 2), PDT, PST), # Transition to Pacific War Time ZoneTransition(datetime(1942, 2, 9, 2), PST, PWT), # Transition from Pacific War Time to Pacific Peace Time ZoneTransition(datetime(1945, 8, 14, 16), PWT, PPT), ZoneTransition(datetime(1945, 9, 30, 2), PPT, PST), ZoneTransition(datetime(2015, 3, 8, 2), PST, PDT), ZoneTransition(datetime(2015, 11, 1, 2), PDT, PST), # After 2038: Rules continue indefinitely ZoneTransition(datetime(2450, 3, 13, 2), PST, PDT), ZoneTransition(datetime(2450, 11, 6, 2), PDT, PST), ] def _America_Santiago(): LMT = ZoneOffset("LMT", timedelta(seconds=-16965), ZERO) SMT = ZoneOffset("SMT", timedelta(seconds=-16965), ZERO) N05 = ZoneOffset("-05", timedelta(seconds=-18000), ZERO) N04 = ZoneOffset("-04", timedelta(seconds=-14400), ZERO) N03 = ZoneOffset("-03", timedelta(seconds=-10800), ONE_H) return [ ZoneTransition(datetime(1890, 1, 1), LMT, SMT), ZoneTransition(datetime(1910, 1, 10), SMT, N05), ZoneTransition(datetime(1916, 7, 1), N05, SMT), ZoneTransition(datetime(2008, 3, 30), N03, N04), ZoneTransition(datetime(2008, 10, 12), N04, N03), ZoneTransition(datetime(2040, 4, 8), N03, N04), ZoneTransition(datetime(2040, 9, 2), N04, N03), ] def _Asia_Tokyo(): JST = ZoneOffset("JST", timedelta(seconds=32400), ZERO) JDT = ZoneOffset("JDT", timedelta(seconds=36000), ONE_H) # Japan had DST from 1948 to 1951, and it was unusual in that # the transition from DST to STD occurred at 25:00, and is # denominated as such in the time zone database return [ ZoneTransition(datetime(1948, 5, 2), JST, JDT), ZoneTransition(datetime(1948, 9, 12, 1), JDT, JST), ZoneTransition(datetime(1951, 9, 9, 1), JDT, JST), ] def _Australia_Sydney(): LMT = ZoneOffset("LMT", timedelta(seconds=36292), ZERO) AEST = ZoneOffset("AEST", timedelta(seconds=36000), ZERO) AEDT = ZoneOffset("AEDT", timedelta(seconds=39600), ONE_H) return [ ZoneTransition(datetime(1895, 2, 1), LMT, AEST), ZoneTransition(datetime(1917, 1, 1, 2), AEST, AEDT), ZoneTransition(datetime(1917, 3, 25, 3), AEDT, AEST), ZoneTransition(datetime(2012, 4, 1, 3), AEDT, AEST), ZoneTransition(datetime(2012, 10, 7, 2), AEST, AEDT), ZoneTransition(datetime(2040, 4, 1, 3), AEDT, AEST), ZoneTransition(datetime(2040, 10, 7, 2), AEST, AEDT), ] def _Europe_Dublin(): LMT = ZoneOffset("LMT", timedelta(seconds=-1521), ZERO) DMT = ZoneOffset("DMT", timedelta(seconds=-1521), ZERO) IST_0 = ZoneOffset("IST", timedelta(seconds=2079), ONE_H) GMT_0 = ZoneOffset("GMT", ZERO, ZERO) BST = ZoneOffset("BST", ONE_H, ONE_H) GMT_1 = ZoneOffset("GMT", ZERO, -ONE_H) IST_1 = ZoneOffset("IST", ONE_H, ZERO) return [ ZoneTransition(datetime(1880, 8, 2, 0), LMT, DMT), ZoneTransition(datetime(1916, 5, 21, 2), DMT, IST_0), ZoneTransition(datetime(1916, 10, 1, 3), IST_0, GMT_0), ZoneTransition(datetime(1917, 4, 8, 2), GMT_0, BST), ZoneTransition(datetime(2016, 3, 27, 1), GMT_1, IST_1), ZoneTransition(datetime(2016, 10, 30, 2), IST_1, GMT_1), ZoneTransition(datetime(2487, 3, 30, 1), GMT_1, IST_1), ZoneTransition(datetime(2487, 10, 26, 2), IST_1, GMT_1), ] def _Europe_Lisbon(): WET = ZoneOffset("WET", ZERO, ZERO) WEST = ZoneOffset("WEST", ONE_H, ONE_H) CET = ZoneOffset("CET", ONE_H, ZERO) CEST = ZoneOffset("CEST", timedelta(seconds=7200), ONE_H) return [ ZoneTransition(datetime(1992, 3, 29, 1), WET, WEST), ZoneTransition(datetime(1992, 9, 27, 2), WEST, CET), ZoneTransition(datetime(1993, 3, 28, 2), CET, CEST), ZoneTransition(datetime(1993, 9, 26, 3), CEST, CET), ZoneTransition(datetime(1996, 3, 31, 2), CET, WEST), ZoneTransition(datetime(1996, 10, 27, 2), WEST, WET), ] def _Europe_London(): LMT = ZoneOffset("LMT", timedelta(seconds=-75), ZERO) GMT = ZoneOffset("GMT", ZERO, ZERO) BST = ZoneOffset("BST", ONE_H, ONE_H) return [ ZoneTransition(datetime(1847, 12, 1), LMT, GMT), ZoneTransition(datetime(2005, 3, 27, 1), GMT, BST), ZoneTransition(datetime(2005, 10, 30, 2), BST, GMT), ZoneTransition(datetime(2043, 3, 29, 1), GMT, BST), ZoneTransition(datetime(2043, 10, 25, 2), BST, GMT), ] def _Pacific_Kiritimati(): LMT = ZoneOffset("LMT", timedelta(seconds=-37760), ZERO) N1040 = ZoneOffset("-1040", timedelta(seconds=-38400), ZERO) N10 = ZoneOffset("-10", timedelta(seconds=-36000), ZERO) P14 = ZoneOffset("+14", timedelta(seconds=50400), ZERO) # This is literally every transition in Christmas Island history return [ ZoneTransition(datetime(1901, 1, 1), LMT, N1040), ZoneTransition(datetime(1979, 10, 1), N1040, N10), # They skipped December 31, 1994 ZoneTransition(datetime(1994, 12, 31), N10, P14), ] return { "Africa/Abidjan": _Africa_Abidjan(), "Africa/Casablanca": _Africa_Casablanca(), "America/Los_Angeles": _America_Los_Angeles(), "America/Santiago": _America_Santiago(), "Australia/Sydney": _Australia_Sydney(), "Asia/Tokyo": _Asia_Tokyo(), "Europe/Dublin": _Europe_Dublin(), "Europe/Lisbon": _Europe_Lisbon(), "Europe/London": _Europe_London(), "Pacific/Kiritimati": _Pacific_Kiritimati(), } return _zone_dump_data() @functools.cache def transition_examples(): zonedump_data = get_zonedump_data() return tuple(zonedump_data.items()) #### # Tests @set_tzpath((), block_tzdata=True) def test_no_tz_data(): """Test what happens when no TZ data is available.""" tz.gettz.cache_clear() NYC = tz.gettz("America/New_York") assert NYC is None def test_tzpath_setting(tmp_path): """Ensure that setting tz.TZPATH changes where `tz.gettz` searches.""" with set_tzpath([tmp_path]): _copy_resource_to( "liliput_tzif", os.path.join(str(tmp_path), "Fictional", "Liliput") ) tz.gettz.cache_clear() fiction_land = tz.gettz("Fictional/Liliput") assert fiction_land is not None @pytest.mark.parametrize( "dt, errtype", [ # Should fail if tzinfo is not `self` (datetime(2019, 1, 1, tzinfo=tz.UTC), ValueError), (datetime(2019, 1, 1), ValueError), # Only works with `datetime` (date(2019, 1, 1), TypeError), (time(0), TypeError), (0, TypeError), ("2019-01-01", TypeError), ], ) def test_fromutc_errors(dt, errtype): """tzinfo.fromutc invocations that raise an error.""" zone = tz.gettz("Europe/London") # Any zone should work with pytest.raises(errtype): zone.fromutc(dt) @as_list def _get_unambiguous_transitions(): for key, zone_transitions in transition_examples(): for zone_transition in zone_transitions: # key, datetime, fold, offset yield ( key, zone_transition.transition - timedelta(days=2), 0, zone_transition.offset_before, ) yield ( key, zone_transition.transition + timedelta(days=2), 0, zone_transition.offset_after, ) @pytest.mark.parametrize("zoneinfo_cache", ["v1", "slim", "fat"], indirect=True) @pytest.mark.parametrize( "transition", _get_unambiguous_transitions(), indirect=True ) def test_unambiguous(transition): """Test times that are *not* ambiguous.""" tzi = tz.gettz(transition.key) dt = transition.dt.replace(tzinfo=tzi) assert dt.tzname() == transition.offset.tzname assert dt.utcoffset() == transition.offset.utcoffset assert dt.dst() == transition.offset.dst @as_list def _get_folds_and_gaps(): for key, zone_transitions in transition_examples(): for zt in zone_transitions: if not zt.fold and not zt.gap: continue test_group = "fold" if zt.fold else "gap" # Cases are of the form key, dt, fold, offset dt = zt.anomaly_start - timedelta(seconds=1) yield (key, dt, 0, zt.offset_before) yield (key, dt, 1, zt.offset_before) dt = zt.anomaly_start yield (key, dt, 0, zt.offset_before) yield (key, dt, 1, zt.offset_after) dt = zt.anomaly_start + timedelta(seconds=1) yield (key, dt, 0, zt.offset_before) yield (key, dt, 1, zt.offset_after) dt = zt.anomaly_end - timedelta(seconds=1) yield (key, dt, 0, zt.offset_before) yield (key, dt, 1, zt.offset_after) dt = zt.anomaly_end yield (key, dt, 0, zt.offset_after) yield (key, dt, 1, zt.offset_after) dt = zt.anomaly_end + timedelta(seconds=1) yield (key, dt, 0, zt.offset_after) yield (key, dt, 1, zt.offset_after) @pytest.mark.parametrize("zoneinfo_cache", ["v1", "slim", "fat"], indirect=True) @pytest.mark.parametrize("transition", _get_folds_and_gaps(), indirect=True) def test_gaps_and_folds(transition): """Test times that are ambiguous.""" tzi = tz.gettz(transition.key) dt = tz.enfold(transition.dt.replace(tzinfo=tzi), transition.fold) assert dt.tzname() == transition.offset.tzname assert dt.utcoffset() == transition.offset.utcoffset assert dt.dst() == transition.offset.dst @as_list def _get_folds_from_utc(): for key, zone_transitions in transition_examples(): for zt in zone_transitions: if not zt.fold: continue dt_utc = zt.transition_utc # key, dt_utc, expected_fold, offset yield (key, dt_utc - SECOND, 0, None) yield (key, dt_utc + SECOND, 1, None) @pytest.mark.parametrize("zoneinfo_cache", ["v1", "slim", "fat"], indirect=True) @pytest.mark.parametrize("transition", _get_folds_from_utc(), indirect=True) def test_folds_from_utc(transition): tzi = tz.gettz(transition.key) dt = transition.dt.astimezone(tzi) assert dt.fold == transition.fold def test_time_fixed_offset(): utc = tz.gettz("UTC") assert isinstance(utc, tz.tzfile) t = time(11, 1, tzinfo=utc) assert t.utcoffset() == ZERO def test_time_varying_offset(): tzi = tz.gettz("America/New_York") t = time(11, 1, tzinfo=tzi) assert t.utcoffset() is None assert t.tzname() is None assert t.dst() is None @functools.cache def weirdzone_test_cases(): _real_cases = {"offset": [], "utc": [], "varying_zones": []} cases = {} def add_cases(f): cases["offset"] = [] cases["utc"] = [] cases["varying_zones"] = [] f() case_found = False for key, values in cases.items(): case_found = True id_base = f.__name__.strip("_") + "-%s" for i, value in enumerate(values): _real_cases[key].append(pytest.param(*value, id=id_base % i)) if not case_found: # pragma: nocover raise ValueError("%s did not add any tests!" % f) @add_cases def _one_transition(): LMT = ZoneOffset("LMT", -timedelta(hours=6, minutes=31, seconds=2)) STD = ZoneOffset("STD", -timedelta(hours=6)) transitions = [ ZoneTransition(datetime(1883, 6, 9, 14), LMT, STD), ] after = "STD6" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/One_Transition") cases["varying_zones"].append((zi,)) dt0 = datetime(1883, 6, 9, 1, tzinfo=zi) dt1 = datetime(1883, 6, 10, 1, tzinfo=zi) for dt, offset in [(dt0, LMT), (dt1, STD)]: dt = dt.replace(tzinfo=zi) cases["offset"].append((dt, offset)) dts = [ ( datetime(1883, 6, 9, 1), datetime(1883, 6, 9, 7, 31, 2, tzinfo=tz.UTC), ), ( datetime(2010, 4, 1, 12), datetime(2010, 4, 1, 18, tzinfo=tz.UTC), ), ] for dt_naive, dt_utc in dts: cases["utc"].append((dt_naive.replace(tzinfo=zi), dt_utc)) @add_cases def _one_transition_fold(): # A zone whose only transition moves the offset backwards, so the # fold it creates has no earlier transition to compare against. AAA = ZoneOffset("AAA", ZERO) BBB = ZoneOffset("BBB", -3 * ONE_H) transitions = [ ZoneTransition(datetime(1976, 12, 1), AAA, BBB), ] after = "BBB3" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/One_Transition_Fold") cases["varying_zones"].append((zi,)) dts = [ (datetime(1976, 11, 30, 20), datetime(1976, 11, 30, 20), 0), (datetime(1976, 11, 30, 22), datetime(1976, 11, 30, 22), 0), (datetime(1976, 11, 30, 21), datetime(1976, 12, 1, 0), 1), (datetime(1976, 11, 30, 22), datetime(1976, 12, 1, 1), 1), (datetime(1976, 11, 30, 23, 59), datetime(1976, 12, 1, 2, 59), 1), (datetime(1976, 12, 1), datetime(1976, 12, 1, 3), 0), (datetime(2020, 1, 1), datetime(2020, 1, 1, 3), 0), ] for dt_naive, dt_utc, fold in dts: dt = tz.enfold(dt_naive.replace(tzinfo=zi), fold=fold) cases["utc"].append((dt, dt_utc.replace(tzinfo=tz.UTC))) @add_cases def _last_transition_fold_before_tzstr(): # Like America/Ciudad_Juarez in slim builds: the last explicit # transition moves the offset backwards, and the TZ string that # takes over after it has a DST rule of its own. LMT = ZoneOffset("LMT", -timedelta(hours=7)) CST = ZoneOffset("CST", -6 * ONE_H) MST = ZoneOffset("MST", -7 * ONE_H) MDT = ZoneOffset("MDT", -6 * ONE_H, ONE_H) transitions = [ ZoneTransition(datetime(2000, 1, 1), LMT, CST), ZoneTransition(datetime(2022, 11, 30), CST, MST), ] after = "MST7MDT,M3.2.0,M11.1.0" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/Last_Transition_Fold") cases["varying_zones"].append((zi,)) dts = [ (datetime(2022, 11, 29, 23, 30), datetime(2022, 11, 30, 5, 30), 0), (datetime(2022, 11, 29, 23), datetime(2022, 11, 30, 6), 1), (datetime(2022, 11, 29, 23, 30), datetime(2022, 11, 30, 6, 30), 1), (datetime(2022, 11, 30, 0, 30), datetime(2022, 11, 30, 7, 30), 0), (datetime(2023, 7, 1, 12), datetime(2023, 7, 1, 18), 0), ] for dt_naive, dt_utc, fold in dts: dt = tz.enfold(dt_naive.replace(tzinfo=zi), fold=fold) cases["utc"].append((dt, dt_utc.replace(tzinfo=tz.UTC))) @add_cases def _last_transition_inside_tzstr_dst(): # Like America/Nuuk in slim builds: the last explicit transition is a # change from DST to standard time with the same offset, which falls # inside a DST period that the TZ string would otherwise give. STD3 = ZoneOffset("-03", -3 * ONE_H) DST2 = ZoneOffset("-02", -2 * ONE_H, ONE_H) STD2 = ZoneOffset("-02", -2 * ONE_H) transitions = [ ZoneTransition(datetime(2023, 3, 25, 22), STD3, DST2), ZoneTransition(datetime(2023, 10, 28, 23), DST2, STD2), ] after = "<-02>2<-01>,M3.5.0/-1,M10.5.0/0" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/Last_Transition_Inside_TZStr_DST") cases["varying_zones"].append((zi,)) for dt, offset in [ (datetime(2023, 10, 28, 22, 30), DST2), (datetime(2023, 10, 28, 23), STD2), (datetime(2023, 10, 28, 23, 30), STD2), (datetime(2023, 10, 29, 1), STD2), ]: for fold in (0, 1): dt_fold = tz.enfold(dt.replace(tzinfo=zi), fold=fold) cases["offset"].append((dt_fold, offset)) dts = [ (datetime(2023, 10, 28, 22, 30), datetime(2023, 10, 29, 0, 30)), (datetime(2023, 10, 28, 23), datetime(2023, 10, 29, 1)), (datetime(2023, 10, 28, 23, 30), datetime(2023, 10, 29, 1, 30)), (datetime(2023, 10, 29, 1), datetime(2023, 10, 29, 3)), # From here on, the TZ string applies (datetime(2024, 7, 1, 12), datetime(2024, 7, 1, 13)), ] for dt_naive, dt_utc in dts: cases["utc"].append( (dt_naive.replace(tzinfo=zi), dt_utc.replace(tzinfo=tz.UTC)) ) @add_cases def _last_transition_same_offset_as_tzstr(): # Like Africa/Casablanca in the rearguard format: the last explicit # transition goes to +01 as DST, and the TZ string that follows it # describes +01 as (negative) DST from a standard offset of +02. The # offset is the same either way, so times in the gap before it get # the TZ string's answer, the same as the times after the gap. STD = ZoneOffset("+00", ZERO) DST = ZoneOffset("+01", ONE_H, ONE_H) AFTER = ZoneOffset("+01", ONE_H, -ONE_H) transitions = [ ZoneTransition(datetime(2087, 3, 1, 3), DST, STD), ZoneTransition(datetime(2087, 5, 11, 2), STD, DST), ] after = "XXX-2<+01>-1,0/0,J365/23" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/Last_Transition_Same_Offset_As_TZStr") cases["varying_zones"].append((zi,)) for dt, fold, offset in [ (datetime(2087, 5, 11, 1, 30), 0, STD), (datetime(2087, 5, 11, 2, 30), 0, STD), (datetime(2087, 5, 11, 2, 30), 1, AFTER), (datetime(2087, 5, 11, 3, 30), 0, AFTER), ]: cases["offset"].append( (tz.enfold(dt.replace(tzinfo=zi), fold), offset) ) @add_cases def _one_transition_zone_dst(): DST = ZoneOffset("DST", ONE_H, ONE_H) transitions = [ ZoneTransition(datetime(1970, 1, 1), DST, DST), ] after = "STD0DST-1,0/0,J365/25" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/One_Zone_DST") cases["varying_zones"].append((zi,)) dts = [ datetime(1900, 3, 1), datetime(1965, 9, 12), datetime(1970, 1, 1), datetime(2010, 11, 3), datetime(2040, 1, 1), ] for dt in dts: dt = dt.replace(tzinfo=zi) cases["offset"].append((dt, DST)) @add_cases def _no_tzstr_zone(): STD = ZoneOffset("STD", ONE_H, ZERO) DST = ZoneOffset("DST", 2 * ONE_H, ONE_H) transitions = [] for year in range(1996, 2000): transitions.append( ZoneTransition(datetime(year, 3, 1, 2), STD, DST) ) transitions.append( ZoneTransition(datetime(year, 11, 1, 2), DST, STD) ) after = "" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/No_TzStr") cases["varying_zones"].append((zi,)) dts = [ (datetime(1995, 1, 1), STD), (datetime(1996, 4, 1), DST), (datetime(1996, 11, 2), STD), (datetime(2001, 1, 1), STD), ] for dt, offset in dts: dt = dt.replace(tzinfo=zi) cases["offset"].append((dt, offset)) @add_cases def _tz_no_transitions_before_only(): # From RFC 8536 Section 3.2: # # If there are no transitions, local time for all timestamps is # specified by the TZ string in the footer if present and nonempty; # otherwise, it is specified by time type 0. offsets = [ ZoneOffset("STD", ZERO, ZERO), ZoneOffset("DST", ONE_H, ONE_H), ] for offset in offsets: # Phantom transition to set time type 0. transitions = [ ZoneTransition(None, offset, offset), ] after = "" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/No_Transitions_%s" % offset.tzname) dts = [ datetime(1900, 1, 1), datetime(1970, 1, 1), datetime(2000, 1, 1), time(12, 0, 0), ] for dt in dts: cases["offset"].append((dt.replace(tzinfo=zi), offset)) @add_cases def _very_large_timestamp_zone(): """Tests using a zone with transitions very far in the past and future. Particularly, this is a concern if something: 1. Attempts to call ``datetime.timestamp`` for a datetime outside of ``[datetime.min, datetime.max]``. 2. Attempts to construct a timedelta outside of ``[timedelta.min, timedelta.max]``. This actually occurs "in the wild", as some time zones on Ubuntu (at least as of 2020) have an initial transition added at ``-2**58``. """ LMT = ZoneOffset("LMT", timedelta(seconds=-968)) GMT = ZoneOffset("GMT", ZERO) transitions = [ (-(1 << 62), LMT, LMT), ZoneTransition(datetime(1912, 1, 1), LMT, GMT), ((1 << 62), GMT, GMT), ] after = "GMT0" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/Large_Transitions") cases["varying_zones"].append((zi,)) offset_cases = [ (datetime.min, LMT), (datetime.max, GMT), (datetime(1911, 12, 31), LMT), (datetime(1912, 1, 2), GMT), ] for dt_naive, offset in offset_cases: dt = dt_naive.replace(tzinfo=zi) cases["offset"].append((dt, offset)) utc_cases = [ (datetime.min, datetime.min + timedelta(seconds=968)), (datetime(1898, 12, 31, 23, 43, 52), datetime(1899, 1, 1)), ( datetime(1911, 12, 31, 23, 59, 59, 999999), datetime(1912, 1, 1, 0, 16, 7, 999999), ), ( datetime(1912, 1, 1, 0, 16, 8), (datetime(1912, 1, 1, 0, 16, 8)), ), (datetime(1970, 1, 1), datetime(1970, 1, 1)), (datetime.max, datetime.max), ] for naive_dt, naive_dt_utc in utc_cases: dt = naive_dt.replace(tzinfo=zi) dt_utc = naive_dt_utc.replace(tzinfo=tz.UTC) cases["utc"].append((dt, dt_utc)) @add_cases def _fixed_offset_phantom_transition_zone(): """A zone with a phantom transition from UTC -> UTC.""" UTC = ZoneOffset("UTC", ZERO, ZERO) transitions = [ZoneTransition(datetime(1970, 1, 1), UTC, UTC)] after = "UTC0" zf = construct_zone(transitions, after) zi = tz.tzfile(zf, key="Etc/Phantom_UTC") cases["offset"].append((datetime(2020, 1, 1, tzinfo=zi), UTC)) cases["offset"].append((time(0, tzinfo=zi), UTC)) NORMAL = 0 FOLD = 1 GAP = 2 def add_tzstr_tests(tzstr, test_cases, varying=True): zi = zone_from_tzstr(tzstr) if varying: cases["varying_zones"].append((zi,)) for dt_naive, offset, dt_type in test_cases: dt = dt_naive.replace(tzinfo=zi) cases["offset"].append((dt, offset)) if dt_type == GAP: continue dt_utc = (dt_naive - offset.utcoffset).replace(tzinfo=tz.UTC) cases["utc"].append((dt, dt_utc)) @add_cases def _tzstr_standard_est5edt(): # Transition to EDT on the 2nd Sunday in March at 4 AM, and # transition back on the first Sunday in November at 3AM tzstr = "EST5EDT,M3.2.0/4:00,M11.1.0/3:00" EST = ZoneOffset("EST", timedelta(hours=-5), ZERO) EDT = ZoneOffset("EDT", timedelta(hours=-4), ONE_H) add_tzstr_tests( tzstr, ( (datetime(2019, 3, 9), EST, NORMAL), (datetime(2019, 3, 10, 3, 59), EST, NORMAL), (datetime(2019, 3, 10, 4, 0), EST, GAP), (tz.enfold(datetime(2019, 3, 10, 4, 0), 1), EDT, GAP), (tz.enfold(datetime(2019, 3, 10, 4, 1), 0), EST, GAP), (tz.enfold(datetime(2019, 3, 10, 4, 1), 1), EDT, GAP), (datetime(2019, 11, 2), EDT, NORMAL), (datetime(2019, 11, 3, 1, 59), EDT, NORMAL), (datetime(2019, 11, 3, 2, 0), EDT, FOLD), (tz.enfold(datetime(2019, 11, 3, 2, 0), 1), EST, FOLD), (datetime(2020, 3, 8, 3, 59), EST, NORMAL), (datetime(2020, 3, 8, 4, 0), EST, GAP), (tz.enfold(datetime(2020, 3, 8, 4, 0), 1), EDT, GAP), (tz.enfold(datetime(2020, 11, 1, 1, 59), 1), EDT, NORMAL), (tz.enfold(datetime(2020, 11, 1, 2, 0), 0), EDT, FOLD), (tz.enfold(datetime(2020, 11, 1, 2, 0), 1), EST, FOLD), ), ) @add_cases def _tzstr_gmt0bst1(): # Transition to BST happens on the last Sunday in March at 1 AM GMT # and the transition back happens the last Sunday in October at 2AM BST tzstr = "GMT0BST-1,M3.5.0/1:00,M10.5.0/2:00" GMT = ZoneOffset("GMT", ZERO, ZERO) BST = ZoneOffset("BST", ONE_H, ONE_H) add_tzstr_tests( tzstr, ( (datetime(2019, 3, 30), GMT, NORMAL), (datetime(2019, 3, 31, 0, 59), GMT, NORMAL), (datetime(2019, 3, 31, 2, 0), BST, NORMAL), (datetime(2019, 10, 26), BST, NORMAL), (tz.enfold(datetime(2019, 10, 27, 0, 59), 1), BST, NORMAL), (tz.enfold(datetime(2019, 10, 27, 1, 0), 0), BST, GAP), (tz.enfold(datetime(2019, 10, 27, 2, 0), 1), GMT, GAP), (datetime(2020, 3, 29, 0, 59), GMT, NORMAL), (datetime(2020, 3, 29, 2, 0), BST, NORMAL), (tz.enfold(datetime(2020, 10, 25, 0, 59), 1), BST, NORMAL), (tz.enfold(datetime(2020, 10, 25, 1, 0), 0), BST, FOLD), (tz.enfold(datetime(2020, 10, 25, 2, 0), 1), GMT, NORMAL), ), ) @add_cases def _tzstr_aest10_aedt(): # Austrialian time zone - DST start is chronologically first tzstr = "AEST-10AEDT,M10.1.0/2,M4.1.0/3" AEST = ZoneOffset("AEST", timedelta(hours=10), ZERO) AEDT = ZoneOffset("AEDT", timedelta(hours=11), ONE_H) add_tzstr_tests( tzstr, ( (datetime(2019, 4, 6), AEDT, NORMAL), (datetime(2019, 4, 7, 1, 59), AEDT, NORMAL), (tz.enfold(datetime(2019, 4, 7, 1, 59), 1), AEDT, NORMAL), (tz.enfold(datetime(2019, 4, 7, 2, 0), 0), AEDT, FOLD), (tz.enfold(datetime(2019, 4, 7, 2, 1), 0), AEDT, FOLD), (tz.enfold(datetime(2019, 4, 7, 2, 0), 1), AEST, FOLD), (tz.enfold(datetime(2019, 4, 7, 2, 1), 1), AEST, FOLD), (tz.enfold(datetime(2019, 4, 7, 3, 0), 0), AEST, NORMAL), (tz.enfold(datetime(2019, 4, 7, 3, 0), 1), AEST, NORMAL), (datetime(2019, 10, 5, 0), AEST, NORMAL), (datetime(2019, 10, 6, 1, 59), AEST, NORMAL), (tz.enfold(datetime(2019, 10, 6, 2, 0), 0), AEST, GAP), (tz.enfold(datetime(2019, 10, 6, 2, 0), 1), AEDT, GAP), (datetime(2019, 10, 6, 3, 0), AEDT, NORMAL), ), ) @add_cases def _tzstr_negative_dst(): # Irish time zone - negative DST tzstr = "IST-1GMT0,M10.5.0,M3.5.0/1" GMT = ZoneOffset("GMT", ZERO, -ONE_H) IST = ZoneOffset("IST", ONE_H, ZERO) add_tzstr_tests( tzstr, ( (datetime(2019, 3, 30), GMT, NORMAL), (datetime(2019, 3, 31, 0, 59), GMT, NORMAL), (datetime(2019, 3, 31, 2, 0), IST, NORMAL), (datetime(2019, 10, 26), IST, NORMAL), (tz.enfold(datetime(2019, 10, 27, 0, 59), 1), IST, NORMAL), (tz.enfold(datetime(2019, 10, 27, 1, 0), 0), IST, FOLD), (tz.enfold(datetime(2019, 10, 27, 1, 0), 1), GMT, FOLD), (tz.enfold(datetime(2019, 10, 27, 2, 0), 1), GMT, NORMAL), (datetime(2020, 3, 29, 0, 59), GMT, NORMAL), (datetime(2020, 3, 29, 2, 0), IST, NORMAL), (tz.enfold(datetime(2020, 10, 25, 0, 59), 1), IST, NORMAL), (tz.enfold(datetime(2020, 10, 25, 1, 0), 0), IST, FOLD), (tz.enfold(datetime(2020, 10, 25, 2, 0), 1), GMT, NORMAL), ), ) @add_cases def _tzstr_fixed_offset_quoted_numerical(): # Pacific/Kosrae: Fixed offset zone with a quoted numerical tzname tzstr = "<+11>-11" add_tzstr_tests( tzstr, ( ( datetime(2020, 1, 1), ZoneOffset("+11", timedelta(hours=11)), NORMAL, ), ), varying=False, ) @add_cases def _tzstr_quoted_std_and_dst_trans_at_24(): # Quoted STD and DST, transitions at 24:00 tzstr = "<-04>4<-03>,M9.1.6/24,M4.1.6/24" M04 = ZoneOffset("-04", timedelta(hours=-4)) M03 = ZoneOffset("-03", timedelta(hours=-3), ONE_H) add_tzstr_tests( tzstr, ( (datetime(2020, 5, 1), M04, NORMAL), (datetime(2020, 11, 1), M03, NORMAL), ), ) @add_cases def _tzstr_permanent_dst(): # Permanent daylight saving time is modeled with transitions at 0/0 # and J365/25, as mentioned in RFC 8536 Section 3.3.1 tzstr = "EST5EDT,0/0,J365/25" EDT = ZoneOffset("EDT", timedelta(hours=-4), ONE_H) add_tzstr_tests( tzstr, ( (datetime(2019, 1, 1), EDT, NORMAL), (datetime(2019, 6, 1), EDT, NORMAL), (datetime(2019, 12, 31, 23, 59, 59, 999999), EDT, NORMAL), (datetime(2020, 1, 1), EDT, NORMAL), (datetime(2020, 3, 1), EDT, NORMAL), (datetime(2020, 6, 1), EDT, NORMAL), (datetime(2020, 12, 31, 23, 59, 59, 999999), EDT, NORMAL), (datetime(2400, 1, 1), EDT, NORMAL), (datetime(2400, 3, 1), EDT, NORMAL), (datetime(2400, 12, 31, 23, 59, 59, 999999), EDT, NORMAL), ), ) @add_cases def _tzstr_transitions_on_julian_day(): # Transitions on March 1st and November 1st of each year tzstr = "AAA3BBB,J60/12,J305/12" AAA = ZoneOffset("AAA", timedelta(hours=-3)) BBB = ZoneOffset("BBB", timedelta(hours=-2), ONE_H) add_tzstr_tests( tzstr, ( (datetime(2019, 1, 1), AAA, NORMAL), (datetime(2019, 2, 28), AAA, NORMAL), (datetime(2019, 3, 1, 11, 59), AAA, NORMAL), (tz.enfold(datetime(2019, 3, 1, 12), 0), AAA, GAP), (tz.enfold(datetime(2019, 3, 1, 12), 1), BBB, GAP), (datetime(2019, 3, 1, 13), BBB, NORMAL), (datetime(2019, 11, 1, 10, 59), BBB, NORMAL), (tz.enfold(datetime(2019, 11, 1, 11), 0), BBB, FOLD), (tz.enfold(datetime(2019, 11, 1, 11), 1), AAA, FOLD), (datetime(2019, 11, 1, 12), AAA, NORMAL), (datetime(2019, 12, 31, 23, 59, 59, 999999), AAA, NORMAL), (datetime(2020, 1, 1), AAA, NORMAL), (datetime(2020, 2, 29), AAA, NORMAL), (datetime(2020, 3, 1, 11, 59), AAA, NORMAL), (tz.enfold(datetime(2020, 3, 1, 12), 0), AAA, GAP), (tz.enfold(datetime(2020, 3, 1, 12), 1), BBB, GAP), (datetime(2020, 3, 1, 13), BBB, NORMAL), (datetime(2020, 11, 1, 10, 59), BBB, NORMAL), (tz.enfold(datetime(2020, 11, 1, 11), 0), BBB, FOLD), (tz.enfold(datetime(2020, 11, 1, 11), 1), AAA, FOLD), (datetime(2020, 11, 1, 12), AAA, NORMAL), (datetime(2020, 12, 31, 23, 59, 59, 999999), AAA, NORMAL), ), ) @add_cases def _tzstr_negative_transition_times(): # Taken from America/Godthab, this rule has a transition on the # Saturday before the last Sunday of March and October, at 22:00 # and 23:00, respectively. This is encoded with negative start # and end transition times. tzstr = "<-03>3<-02>,M3.5.0/-2,M10.5.0/-1" N03 = ZoneOffset("-03", timedelta(hours=-3)) N02 = ZoneOffset("-02", timedelta(hours=-2), ONE_H) add_tzstr_tests( tzstr, ( (datetime(2020, 3, 27), N03, NORMAL), (datetime(2020, 3, 28, 21, 59, 59), N03, NORMAL), (tz.enfold(datetime(2020, 3, 28, 22), 0), N03, GAP), (tz.enfold(datetime(2020, 3, 28, 22), 1), N02, GAP), (datetime(2020, 3, 28, 23), N02, NORMAL), (datetime(2020, 10, 24, 21), N02, NORMAL), (tz.enfold(datetime(2020, 10, 24, 22), 0), N02, FOLD), (tz.enfold(datetime(2020, 10, 24, 22), 1), N03, FOLD), (datetime(2020, 10, 24, 23), N03, NORMAL), ), ) @add_cases def _tzstr_minute_second_transition_times(): # Transition times with minutes and seconds tzstr = "AAA3BBB,M3.2.0/01:30,M11.1.0/02:15:45" AAA = ZoneOffset("AAA", timedelta(hours=-3)) BBB = ZoneOffset("BBB", timedelta(hours=-2), ONE_H) add_tzstr_tests( tzstr, ( (datetime(2012, 3, 11, 1, 0), AAA, NORMAL), (tz.enfold(datetime(2012, 3, 11, 1, 30), 0), AAA, GAP), (tz.enfold(datetime(2012, 3, 11, 1, 30), 1), BBB, GAP), (datetime(2012, 3, 11, 2, 30), BBB, NORMAL), (datetime(2012, 11, 4, 1, 15, 44, 999999), BBB, NORMAL), (tz.enfold(datetime(2012, 11, 4, 1, 15, 45), 0), BBB, FOLD), (tz.enfold(datetime(2012, 11, 4, 1, 15, 45), 1), AAA, FOLD), (datetime(2012, 11, 4, 2, 15, 45), AAA, NORMAL), ), ) return _real_cases def _fixed_offset_zone(): STD = ZoneOffset("STD", -5 * ONE_H) return tz.tzfile( construct_zone([ZoneTransition(datetime(2020, 1, 1), STD, STD)], "STD5") ) @pytest.mark.parametrize( "dt", [ datetime(2019, 12, 31, 23, 30), datetime(2020, 1, 1), datetime(2020, 1, 1, 0, 30), datetime(2100, 1, 1), ], ) def test_fixed_offset_never_ambiguous_or_imaginary(dt): """A fixed-offset zone has no ambiguous or imaginary times.""" zone = _fixed_offset_zone() for fold in (0, 1): dt_fold = tz.enfold(dt.replace(tzinfo=zone), fold=fold) assert not zone.is_ambiguous(dt_fold) assert not tz.datetime_ambiguous(dt_fold) assert tz.datetime_exists(dt_fold) assert dt_fold.utcoffset() == -5 * ONE_H @pytest.mark.parametrize( "zone", [ pytest.param(_fixed_offset_zone(), id="fixed"), pytest.param( tz.tzfile( construct_zone( [ ZoneTransition( datetime(2020, 11, 1, 2), ZoneOffset("DST", -4 * ONE_H, ONE_H), ZoneOffset("STD", -5 * ONE_H), ) ], "STD5", ) ), id="varying", ), ], ) def test_is_ambiguous_none(zone): """is_ambiguous(None) is False, as it is for other tzinfo classes.""" assert zone.is_ambiguous(None) is False @pytest.mark.parametrize("dt, offset", weirdzone_test_cases()["offset"]) def test_weirdzone_offsets(dt, offset): assert dt.tzname() == offset.tzname assert dt.utcoffset() == offset.utcoffset assert dt.dst() == offset.dst @pytest.mark.parametrize("dt, dt_utc", weirdzone_test_cases()["utc"]) def test_weirdzone_utc(dt, dt_utc): assert dt.tzinfo is not None assert dt.astimezone(tz.UTC) == dt_utc # Comparisons between datetimes with the same tzinfo ignore fold, so # also check the round trip back to UTC and, for ambiguous times, fold. dt_act = dt_utc.astimezone(dt.tzinfo) assert dt_act == dt assert dt_act.astimezone(tz.UTC) == dt_utc if tz.datetime_ambiguous(dt): assert dt_act.fold == dt.fold @pytest.mark.parametrize("zone", weirdzone_test_cases()["varying_zones"]) def test_weirdzone_time_none(zone): t = time(12, 0, 0, tzinfo=zone) assert t.tzname() is None assert t.utcoffset() is None assert t.dst() is None def test_empty_zone(): zf = construct_zone([], "") with pytest.raises(ValueError): tz.tzfile(zf) @pytest.mark.parametrize("version", [1, 2, 3]) def test_no_transitions_uses_time_type_0(version): """Without transitions or a TZ string, local time is time type 0.""" STD = ZoneOffset("STD", ZERO) ALT = ZoneOffset("ALT", ONE_H, ONE_H) # A transition without a time just adds the local time types to the file zone = tz.tzfile( construct_zone([ZoneTransition(None, STD, ALT)], "", version=version) ) for dt in [ datetime(1900, 1, 1), datetime(2020, 7, 1), datetime(2100, 1, 1), ]: dt = dt.replace(tzinfo=zone) assert dt.utcoffset() == ZERO assert dt.dst() == ZERO assert dt.tzname() == "STD" def test_eq_no_transitions(): """Zones with no transitions must compare by their fixed offset.""" plus_five = zone_from_tzstr("<+05>-5") minus_five = zone_from_tzstr("<-05>5") utc = zone_from_tzstr("UTC0") assert plus_five == zone_from_tzstr("<+05>-5") assert plus_five != minus_five assert plus_five != utc assert minus_five != utc def test_eq_same_transitions_different_tzstr(): """Zones that differ only in the TZ string are not equal.""" STD = ZoneOffset("STD", ZERO) DST = ZoneOffset("DST", ONE_H, ONE_H) transitions = [ZoneTransition(datetime(2010, 3, 14, 2), STD, DST)] with_rule = tz.tzfile(construct_zone(transitions, "STD0DST,M3.2.0,M11.1.0")) same_rule = tz.tzfile(construct_zone(transitions, "STD0DST,M3.2.0,M11.1.0")) no_rule = tz.tzfile(construct_zone(transitions, "")) assert with_rule == same_rule assert with_rule != no_rule @pytest.mark.parametrize("strip", [1, 2, 4, 8]) def test_truncated_footer(strip): """A file cut off inside the TZ string footer must not hang.""" zf = construct_zone([], "EST5EDT,M3.2.0,M11.1.0") data = zf.read() assert data.endswith(b"\n") with pytest.raises(ValueError): tz.tzfile(io.BytesIO(data[:-strip])) def _zone_for_stream_tests(): STD = ZoneOffset("STD", -5 * ONE_H) DST = ZoneOffset("DST", -4 * ONE_H, ONE_H) return construct_zone( [ ZoneTransition(datetime(2020, 3, 8, 2), STD, DST), ZoneTransition(datetime(2020, 11, 1, 2), DST, STD), ], "STD5DST,M3.2.0,M11.1.0", ).read() def test_tzfile_from_pipe(): """A zone can be read from a stream that cannot seek.""" data = _zone_for_stream_tests() expected = tz.tzfile(io.BytesIO(data)) read_fd, write_fd = os.pipe() os.write(write_fd, data) os.close(write_fd) # On Windows, pipes claim to be seekable even though they aren't. with open(read_fd, "rb") as f: zone = tz.tzfile(f, filename="pipe") assert zone == expected assert datetime(2030, 7, 1, tzinfo=zone).tzname() == "DST" def test_tzfile_from_read_only_object(): """A zone can be read from an object that only has a read() method.""" class ReadOnly: def __init__(self, data): self._stream = io.BytesIO(data) def read(self, *args): return self._stream.read(*args) data = _zone_for_stream_tests() zone = tz.tzfile(ReadOnly(data), filename="read-only") assert zone == tz.tzfile(io.BytesIO(data)) @pytest.fixture def tzpath_and_outside_zone(tmp_path): """A TZPATH entry, and a zone in a sibling directory outside of it.""" STD = ZoneOffset("STD", ZERO) data = construct_zone( [ZoneTransition(datetime(2020, 1, 1), STD, STD)], "STD0" ).read() tzpath = tmp_path / "zoneinfo" outside = tmp_path / "outside" for directory in (tzpath / "Fictional", outside): os.makedirs(str(directory)) (tzpath / "Fictional" / "Inside").write_bytes(data) (outside / "Outside").write_bytes(data) with set_tzpath((str(tzpath),), block_tzdata=True): tz.gettz.cache_clear() yield tz.gettz.cache_clear() @pytest.mark.parametrize( "key", [ "../outside/Outside", "Fictional/../../outside/Outside", "./../outside/Outside", ], ) def test_gettz_key_outside_tzpath_is_an_error(tzpath_and_outside_zone, key): with warnings.catch_warnings(): warnings.resetwarnings() with pytest.raises(tz.DeprecatedTzKeyWarning): tz.gettz(key) def test_gettz_key_outside_tzpath_can_be_allowed(tzpath_and_outside_zone): with warnings.catch_warnings(record=True) as record: warnings.resetwarnings() warnings.simplefilter("always", category=tz.DeprecatedTzKeyWarning) zone = tz.gettz("../outside/Outside") assert isinstance(zone, tz.tzfile) assert [w.category for w in record] == [tz.DeprecatedTzKeyWarning] assert ( os.path.splitext(record[0].filename)[0] == os.path.splitext(__file__)[0] ) @pytest.mark.parametrize( "key", ["Fictional/Inside", "Fictional/../Fictional/Inside", "./Fictional/Inside"], ) def test_gettz_key_inside_tzpath_does_not_warn(tzpath_and_outside_zone, key): with warnings.catch_warnings(): warnings.resetwarnings() warnings.simplefilter("error") assert isinstance(tz.gettz(key), tz.tzfile) @pytest.mark.parametrize("version", [1, 2, 3, 4]) @pytest.mark.parametrize( "leap_seconds", [ pytest.param((), id="no_leap_seconds"), pytest.param(((78796800, 1), (94694401, 2)), id="leap_seconds"), # Version 4 files may truncate the start of the leap second table, so # that the first correction is not +1 or -1. pytest.param(((1435708825, 26), (1483228826, 27)), id="truncated"), ], ) @pytest.mark.parametrize("indicators", [False, True]) def test_leap_seconds_and_indicators(version, leap_seconds, indicators): """Leap second records and indicators don't change how a zone behaves.""" STD = ZoneOffset("STD", -5 * ONE_H) DST = ZoneOffset("DST", -4 * ONE_H, ONE_H) transitions = [ ZoneTransition(datetime(2020, 3, 8, 2), STD, DST), ZoneTransition(datetime(2020, 11, 1, 2), DST, STD), ] after = "STD5DST,M3.2.0,M11.1.0" expected = tz.tzfile(construct_zone(transitions, after, version=version)) zone = tz.tzfile( construct_zone( transitions, after, version=version, leap_seconds=leap_seconds, indicators=indicators, ) ) assert zone == expected for dt_utc in [ datetime(2019, 12, 1, tzinfo=tz.UTC), datetime(2020, 7, 1, tzinfo=tz.UTC), datetime(2020, 11, 1, 5, 30, tzinfo=tz.UTC), datetime(2020, 11, 1, 6, 30, tzinfo=tz.UTC), datetime(2030, 7, 1, tzinfo=tz.UTC), ]: dt = dt_utc.astimezone(zone) dt_expected = dt_utc.astimezone(expected) assert dt.replace(tzinfo=None) == dt_expected.replace(tzinfo=None) assert dt.fold == dt_expected.fold assert dt.tzname() == dt_expected.tzname() assert dt.utcoffset() == dt_expected.utcoffset() @pytest.mark.parametrize("version", [1, 2, 3, 4]) @pytest.mark.parametrize("indicators", [False, True]) def test_stream_position_after_leap_seconds(version, indicators): """Reading a TZif file leaves the stream at the end of the file.""" STD = ZoneOffset("STD", -5 * ONE_H) DST = ZoneOffset("DST", -4 * ONE_H, ONE_H) transitions = [ ZoneTransition(datetime(2020, 3, 8, 2), STD, DST), ZoneTransition(datetime(2020, 11, 1, 2), DST, STD), ] zonefile = construct_zone( transitions, "STD5DST,M3.2.0,M11.1.0", version=version, leap_seconds=((78796800, 1), (94694401, 2)), indicators=indicators, ) trailer = b"Data after the TZif file" stream = io.BytesIO(zonefile.getvalue() + trailer) tz.tzfile(stream) assert stream.read() == trailer @pytest.mark.parametrize("version", [1, 2, 3, 4]) def test_update_tzif_file_to_v1(tmp_path, version): """update_tzif converts TZif files of any version to Version 1.""" import asyncio from .resources import update_tzif STD = ZoneOffset("STD", -5 * ONE_H) DST = ZoneOffset("DST", -4 * ONE_H, ONE_H) transitions = [ ZoneTransition(datetime(2020, 3, 8, 2), STD, DST), ZoneTransition(datetime(2020, 11, 1, 2), DST, STD), ] def make_zone(version): return construct_zone( transitions, "STD5DST,M3.2.0,M11.1.0", version=version, leap_seconds=((78796800, 1), (94694401, 2)), indicators=True, ).getvalue() in_path = tmp_path / "in" out_path = tmp_path / "out" in_path.write_bytes(make_zone(version)) asyncio.run(update_tzif._file_to_v1(in_path, out_path)) assert out_path.read_bytes() == make_zone(1) def _assert_constant_offset_around_new_year(zone, offset, years): for year in years: base = datetime(year, 12, 31, 18, tzinfo=tz.UTC) for minutes in range(0, 12 * 60, 15): dt_utc = base + timedelta(minutes=minutes) dt = dt_utc.astimezone(zone) assert dt.utcoffset() == offset, dt_utc assert dt.astimezone(tz.UTC) == dt_utc for fold in (0, 1): wall = tz.enfold(dt, fold=fold) assert wall.utcoffset() == offset, (wall, fold) assert tz.datetime_exists(wall) assert not tz.datetime_ambiguous(wall) @as_list def _near_min_and_max_year_cases(): EST = -5 * ONE_H EDT = -4 * ONE_H STD = ZERO DST = ONE_H for dt in [ datetime(1, 1, 1, 0, 30), datetime(1, 1, 1, 12), datetime(1, 1, 5, 12), datetime(9999, 12, 28, 6, 55), datetime(9999, 12, 31, 12), datetime(9999, 12, 31, 23, 30), ]: yield "EST5EDT,M3.2.0,M11.1.0", dt, EST yield "<+00>0<+01>,0/0,J365/25", dt, DST # DST all year: the rules for year 0 end DST at 01:00 on January 1st # of year 1, just as the rules for year 1 start it, so there's no gap. yield "EST5EDT,0/0,J365/25", dt, EDT # The rules for year 10000 start DST on 9999-12-31. for dt, offset in [ (datetime(1, 1, 1, 12), DST), (datetime(9999, 4, 10, 12), STD), (datetime(9999, 12, 30, 12), STD), (datetime(9999, 12, 31, 12), DST), (datetime(9999, 12, 31, 23, 30), DST), ]: yield "STD0DST,J1/-24,J100/0", dt, offset @pytest.mark.parametrize("tz_str, dt, offset", _near_min_and_max_year_cases()) def test_tzstr_near_min_and_max_year(tz_str, dt, offset): """The rules for years 0 and 10000 apply to the dates around them.""" zone = tz.tzfile(construct_zone([], tz_str)) for fold in (0, 1): dt_fold = tz.enfold(dt.replace(tzinfo=zone), fold=fold) assert dt_fold.utcoffset() == offset, fold try: dt_utc = (dt - offset).replace(tzinfo=tz.UTC) except OverflowError: # The UTC time is past the end of what datetime can represent return dt_local = dt_utc.astimezone(zone) assert dt_local.replace(tzinfo=None) == dt assert dt_local.utcoffset() == offset @pytest.mark.parametrize( "tz_str", [ # DST all year, written the way zic writes it: each year's DST period # ends at the same instant as the next one starts. "<+00>0<+01>,J1/0,J365/25", # The same, with negative DST, as in the rearguard format for # Africa/Casablanca. "XXX-2<+01>-1,J1/0,J365/23", # The same two, spelled the way zic actually writes them "<+00>0<+01>,0/0,J365/25", "XXX-2<+01>-1,0/0,J365/23", ], ) def test_tzstr_dst_all_year(tz_str): """Rules whose transitions meet at the new year don't create a gap.""" zone = tz.tzfile(construct_zone([], tz_str)) _assert_constant_offset_around_new_year(zone, ONE_H, (2023, 2024, 2100)) @pytest.mark.parametrize( "tz_str, std_dts, dst_dts", [ # "n" counts from 0, so day 10 is January 11th ( "STD0DST-1,10/0,J100/0", [datetime(2021, 1, 10, 12)], [datetime(2021, 1, 11, 12)], ), # ... and it includes February 29th: day 59 is February 29th in leap # years and March 1st otherwise ( "STD0DST-1,59/0,300/0", [datetime(2024, 2, 28, 12), datetime(2023, 2, 28, 12)], [datetime(2024, 2, 29, 12), datetime(2023, 3, 1, 12)], ), # "Jn" counts from 1 and never counts February 29th, so J59 is always # February 28th and J60 is always March 1st ( "STD0DST-1,J59/0,J300/0", [datetime(2024, 2, 27, 12), datetime(2023, 2, 27, 12)], [datetime(2024, 2, 28, 12), datetime(2023, 2, 28, 12)], ), ( "STD0DST-1,J60/0,J300/0", [datetime(2024, 2, 29, 12), datetime(2023, 2, 28, 12)], [datetime(2024, 3, 1, 12), datetime(2023, 3, 1, 12)], ), ], ) def test_tzstr_day_of_year_rules(tz_str, std_dts, dst_dts): """The dates of "n" and "Jn" rules match POSIX (and glibc).""" zone = tz.tzfile(construct_zone([], tz_str)) for dts, tzname in ((std_dts, "STD"), (dst_dts, "DST")): for dt in dts: assert dt.replace(tzinfo=zone).tzname() == tzname, dt dt_utc = dt.replace(tzinfo=tz.UTC) assert dt_utc.astimezone(zone).tzname() == tzname, dt_utc @pytest.mark.parametrize("version", [1, 2, 3]) def test_truncated_file(version): """A file cut off anywhere is either still valid or raises ValueError.""" STD = ZoneOffset("STD", -5 * ONE_H) DST = ZoneOffset("DST", -4 * ONE_H, ONE_H) zf = construct_zone( [ ZoneTransition(datetime(2020, 3, 8, 2), STD, DST), ZoneTransition(datetime(2020, 11, 1, 2), DST, STD), ], "STD5DST,M3.2.0,M11.1.0", version=version, ) data = zf.read() for length in range(len(data)): try: tz.tzfile(io.BytesIO(data[:length])) except ValueError: pass def test_truncated_file_on_tzpath(tmp_path): """gettz skips a truncated file on TZPATH like any other invalid file.""" STD = ZoneOffset("STD", ZERO) data = construct_zone( [ZoneTransition(datetime(2020, 1, 1), STD, STD)], "STD0" ).read() zone_dir = tmp_path / "Fictional" zone_dir.mkdir() # Cut off inside the header (zone_dir / "Truncated").write_bytes(data[:30]) with set_tzpath((str(tmp_path),), block_tzdata=True): tz.gettz.cache_clear() assert tz.gettz("Fictional/Truncated") is None def _valid_tzif_data(): STD = ZoneOffset("STD", ZERO) return construct_zone( [ZoneTransition(datetime(2020, 1, 1), STD, STD)], "STD0" ).read() def _unreadable_file(path): path.write_bytes(_valid_tzif_data()) os.chmod(str(path), 0) if os.access(str(path), os.R_OK): # pragma: nocover # e.g. running as root pytest.skip("Cannot make a file unreadable here") INVALID_TZPATH_FILES = [ pytest.param( lambda path: path.write_bytes(b"Not a TZif file\n"), id="not_tzif" ), pytest.param( lambda path: path.write_bytes(_valid_tzif_data()[:30]), id="truncated" ), pytest.param( _unreadable_file, id="unreadable", marks=pytest.mark.skipif(IS_WIN, reason="POSIX permissions"), ), ] @pytest.mark.parametrize("make_invalid", INVALID_TZPATH_FILES) def test_gettz_skips_invalid_file_on_tzpath(tmp_path, make_invalid): """An invalid file on TZPATH falls through to the next TZPATH entry.""" first = tmp_path / "first" / "Fictional" second = tmp_path / "second" / "Fictional" for directory in (first, second): os.makedirs(str(directory)) make_invalid(first / "Zone") (second / "Zone").write_bytes(_valid_tzif_data()) tzpath = (str(tmp_path / "first"), str(tmp_path / "second")) with set_tzpath(tzpath, block_tzdata=True): zone = tz.gettz("Fictional/Zone") assert isinstance(zone, tz.tzfile) # On Windows the key's "/" ends up in the path as it is assert os.path.normpath(zone._filename) == str(second / "Zone") @pytest.mark.parametrize("make_invalid", INVALID_TZPATH_FILES) def test_gettz_invalid_file_on_tzpath_falls_back_to_tzdata( tmp_path, make_invalid ): """An invalid file on TZPATH falls through to the tzdata package.""" pytest.importorskip("tzdata") with set_tzpath((), block_tzdata=False): expected = tz.gettz("America/New_York") os.makedirs(str(tmp_path / "America")) make_invalid(tmp_path / "America" / "New_York") with set_tzpath((str(tmp_path),), block_tzdata=False): zone = tz.gettz("America/New_York") assert isinstance(zone, tz.tzfile) assert zone == expected assert zone._filename != str(tmp_path / "America" / "New_York") @pytest.mark.skipif(IS_WIN, reason="The Windows registry has these names") @pytest.mark.parametrize("name", ["UTC", "GMT"]) def test_gettz_utc_without_time_zone_data(name): """With no time zone data at all, "UTC" and "GMT" are still UTC.""" with set_tzpath((), block_tzdata=True): assert tz.gettz(name) is tz.UTC @pytest.mark.skipif(IS_WIN, reason="The Windows registry has these names") def test_gettz_local_abbreviation_without_time_zone_data(): """Abbreviations of the local zone that aren't keys give tzlocal().""" names = [ name for name in time_module.tzname if name and not any(c.isdigit() for c in name) ] if not names: # pragma: nocover pytest.skip("The local zone has no alphabetic abbreviations") with set_tzpath((), block_tzdata=True): for name in names: assert isinstance(tz.gettz(name), tz.tzlocal) def test_missing_footer_newline(): """Version 2+ files must have a newline before the TZ string.""" zf = construct_zone([], "EST5EDT,M3.2.0,M11.1.0") data = zf.read() # The footer is "\n\n"; drop the leading newline. footer_start = data.rfind(b"\n", 0, len(data) - 1) data = data[:footer_start] + data[footer_start + 1 :] with pytest.raises(ValueError): tz.tzfile(io.BytesIO(data)) def test_invalid_transition_index(): """A transition index past the end of the ttinfo table is an error.""" STD = ZoneOffset("STD", ZERO) DST = ZoneOffset("DST", ONE_H, ONE_H) zf = construct_zone( [ ZoneTransition(datetime(2026, 3, 1, 2), STD, DST), ZoneTransition(datetime(2026, 11, 1, 2), DST, STD), ], after="", version=1, ) data = bytearray(zf.read()) timecnt = struct.unpack_from(">l", data, 32)[0] idx_offset = 44 + timecnt * 4 data[idx_offset + 1] = 2 # typecnt is 2, so index 2 is out of bounds with pytest.raises(ValueError): tz.tzfile(io.BytesIO(bytes(data))) def test_transition_lookahead_out_of_bounds(): """Inferring DST offsets must not look past the last transition.""" STD = ZoneOffset("STD", ZERO) DST = ZoneOffset("DST", ONE_H, ONE_H) EXT = ZoneOffset("EXT", ONE_H) zf = construct_zone( [ ZoneTransition(datetime(2026, 3, 1), STD, DST), ZoneTransition(datetime(2026, 6, 1), DST, EXT), ZoneTransition(datetime(2026, 9, 1), EXT, DST), ], after="", ) assert tz.tzfile(zf) is not None EXTREME_TZSTRS = [ # Extreme offset hour "AAA24", "AAA+24", "AAA-24", "AAA24BBB,J60/2,J300/2", "AAA+24BBB,J60/2,J300/2", "AAA-24BBB,J60/2,J300/2", "AAA4BBB24,J60/2,J300/2", "AAA4BBB+24,J60/2,J300/2", "AAA4BBB-24,J60/2,J300/2", # Extreme offset minutes "AAA4:00BBB,J60/2,J300/2", "AAA4:59BBB,J60/2,J300/2", "AAA4BBB5:00,J60/2,J300/2", "AAA4BBB5:59,J60/2,J300/2", # Extreme offset seconds "AAA4:00:00BBB,J60/2,J300/2", "AAA4:00:59BBB,J60/2,J300/2", "AAA4BBB5:00:00,J60/2,J300/2", "AAA4BBB5:00:59,J60/2,J300/2", # Extreme total offset "AAA24:59:59BBB5,J60/2,J300/2", "AAA-24:59:59BBB5,J60/2,J300/2", "AAA4BBB24:59:59,J60/2,J300/2", "AAA4BBB-24:59:59,J60/2,J300/2", # Extreme months "AAA4BBB,M12.1.1/2,M1.1.1/2", "AAA4BBB,M1.1.1/2,M12.1.1/2", # Extreme weeks "AAA4BBB,M1.5.1/2,M1.1.1/2", "AAA4BBB,M1.1.1/2,M1.5.1/2", # Extreme weekday "AAA4BBB,M1.1.6/2,M2.1.1/2", "AAA4BBB,M1.1.1/2,M2.1.6/2", # Extreme numeric offset "AAA4BBB,0/2,20/2", "AAA4BBB,0/2,0/14", "AAA4BBB,20/2,365/2", "AAA4BBB,365/2,365/14", # Extreme julian offset "AAA4BBB,J1/2,J20/2", "AAA4BBB,J1/2,J1/14", "AAA4BBB,J20/2,J365/2", "AAA4BBB,J365/2,J365/14", # Leading-zero day-of-year "AAA4BBB,J001/2,J065/2", "AAA4BBB,001/2,065/2", # Extreme transition hour "AAA4BBB,J60/167,J300/2", "AAA4BBB,J60/+167,J300/2", "AAA4BBB,J60/-167,J300/2", "AAA4BBB,J60/2,J300/167", "AAA4BBB,J60/2,J300/+167", "AAA4BBB,J60/2,J300/-167", # Extreme transition minutes "AAA4BBB,J60/2:00,J300/2", "AAA4BBB,J60/2:59,J300/2", "AAA4BBB,J60/2,J300/2:00", "AAA4BBB,J60/2,J300/2:59", # Extreme transition seconds "AAA4BBB,J60/2:00:00,J300/2", "AAA4BBB,J60/2:00:59,J300/2", "AAA4BBB,J60/2,J300/2:00:00", "AAA4BBB,J60/2,J300/2:00:59", # Extreme total transition time "AAA4BBB,J60/167:59:59,J300/2", "AAA4BBB,J60/-167:59:59,J300/2", "AAA4BBB,J60/2,J300/167:59:59", "AAA4BBB,J60/2,J300/-167:59:59", ] @pytest.mark.parametrize("tzstr", EXTREME_TZSTRS) def test_extreme_tzstr(tzstr): """TZ strings at the edge of the valid range are accepted.""" assert zone_from_tzstr(tzstr) is not None INVALID_TZSTRS = [ "PST8PDT", # DST but no transition specified # The std offset is required (POSIX TZ grammar) "AAA", "A", "AA", "B", "+11", # Unquoted alphanumeric "GMT,M3.2.0/2,M11.1.0/3", # Transition rule but no DST # Transition rules but no DST abbreviation "EST5,M3.2.0,M11.1.0", "<+04>-4,J60,J300", "AAA3,0/0,J365/25", "GMT0+11,M3.2.0/2,M11.1.0/3", # Unquoted alphanumeric in DST # Unquoted abbreviation with embedded or leading whitespace "AB C3", " A B 3", "AAA4BB B,J60/2,J300/2", # Embedded whitespace in DST # Empty quoted abbreviation "<>5", "AAA4<>,M3.2.0/2,M11.1.0/3", "PST8PDT,M3.2.0/2", # Only one transition rule # Invalid offset hours "AAA168", "AAA+168", "AAA-168", "AAA168BBB,J60/2,J300/2", "AAA+168BBB,J60/2,J300/2", "AAA-168BBB,J60/2,J300/2", "AAA4BBB168,J60/2,J300/2", "AAA4BBB+168,J60/2,J300/2", "AAA4BBB-168,J60/2,J300/2", # Invalid offset minutes "AAA4:0BBB,J60/2,J300/2", "AAA4:100BBB,J60/2,J300/2", "AAA4BBB5:0,J60/2,J300/2", "AAA4BBB5:100,J60/2,J300/2", # Invalid offset seconds "AAA4:00:0BBB,J60/2,J300/2", "AAA4:00:100BBB,J60/2,J300/2", "AAA4BBB5:00:0,J60/2,J300/2", "AAA4BBB5:00:100,J60/2,J300/2", # Completely invalid dates "AAA4BBB,M1443339,M11.1.0/3", "AAA4BBB,M3.2.0/2,0349309483959c", "AAA4BBB,,J300/2", "AAA4BBB,z,J300/2", "AAA4BBB,J60/2,", "AAA4BBB,J60/2,z", # Invalid months "AAA4BBB,M13.1.1/2,M1.1.1/2", "AAA4BBB,M1.1.1/2,M13.1.1/2", "AAA4BBB,M0.1.1/2,M1.1.1/2", "AAA4BBB,M1.1.1/2,M0.1.1/2", # Invalid weeks "AAA4BBB,M1.6.1/2,M1.1.1/2", "AAA4BBB,M1.1.1/2,M1.6.1/2", # Invalid weekday "AAA4BBB,M1.1.7/2,M2.1.1/2", "AAA4BBB,M1.1.1/2,M2.1.7/2", # Invalid Mm.w.d separator "AAA4BBB,M3.2X0,M11.1.0", "AAA4BBB,M3.2.0,M11.1X0", "AAA4BBB,M3.2-0,M11.1.0/3", "AAA4BBB,M3.2.0/2,M11.1:0", # Invalid numeric offset "AAA4BBB,-1/2,20/2", "AAA4BBB,1/2,-1/2", "AAA4BBB,367,20/2", "AAA4BBB,1/2,367/2", # Invalid julian offset "AAA4BBB,J0/2,J20/2", "AAA4BBB,J20/2,J366/2", # Non-digit day-of-year "AAA4BBB,J1_0,J300/2", "AAA4BBB,J60/2,J30_0/2", "AAA4BBB,1_0,J300/2", "AAA4BBB,J+1,J300/2", "AAA4BBB,J 1,J300/2", "AAA4BBB, 1,J300/2", "AAA4BBB,J0001,J300/2", "AAA4BBB,0001,J300/2", # Invalid transition time "AAA4BBB,J60/2/3,J300/2", "AAA4BBB,J60/2,J300/2/3", # Invalid transition hour "AAA4BBB,J60/168,J300/2", "AAA4BBB,J60/+168,J300/2", "AAA4BBB,J60/-168,J300/2", "AAA4BBB,J60/2,J300/168", "AAA4BBB,J60/2,J300/+168", "AAA4BBB,J60/2,J300/-168", # Invalid transition minutes "AAA4BBB,J60/2:0,J300/2", "AAA4BBB,J60/2:100,J300/2", "AAA4BBB,J60/2,J300/2:0", "AAA4BBB,J60/2,J300/2:100", # Invalid transition seconds "AAA4BBB,J60/2:00:0,J300/2", "AAA4BBB,J60/2:00:100,J300/2", "AAA4BBB,J60/2,J300/2:00:0", "AAA4BBB,J60/2,J300/2:00:100", ] @pytest.mark.parametrize("tzstr", INVALID_TZSTRS) def test_invalid_tzstr(tzstr): """Malformed TZ strings raise ValueError naming the string.""" import re with pytest.raises(ValueError, match=re.escape(tzstr)): zone_from_tzstr(tzstr) @pytest.mark.parametrize( "tzstr", [ # Non-ASCII letter in the abbreviation "AB" + chr(0xC0) + "C3", # Non-ASCII digit in the day-of-year "AAA4BBB,J" + chr(0x661) + ",J300/2", ], ) def test_invalid_tzstr_non_ascii(tzstr): with pytest.raises(ValueError): zone_from_tzstr(tzstr, encoding="utf-8") @pytest.mark.parametrize( "tz_str, dt, expected_seconds", [ ("<-0044>0:44:30", datetime(2020, 1, 15), -2670), ("AAA0:44:30BBB,M3.2.0,M11.1.0", datetime(2020, 1, 15), -2670), ("AAA0:44:30BBB,M3.2.0,M11.1.0", datetime(2020, 7, 15), 930), ("AAA0:44:30BBB-0:44:30,M3.2.0,M11.1.0", datetime(2020, 7, 15), 2670), ], ) def test_sub_minute_offset_tz_str(tz_str, dt, expected_seconds): """Sub-minute offsets in the TZ string are kept exact, like those in the file.""" GMT = ZoneOffset("GMT", ZERO) zone = tz.tzfile( construct_zone([ZoneTransition(datetime(1900, 1, 1), GMT, GMT)], tz_str) ) expected = timedelta(seconds=expected_seconds) assert dt.replace(tzinfo=zone).utcoffset() == expected def test_tzfile_repr(): """When the key is specified with a file object, it should be used in the repr.""" GMT = ZoneOffset("GMT", ZERO, ZERO) BST = ZoneOffset("BST", ONE_H, ONE_H) zf = construct_zone( [ ZoneTransition(datetime(2005, 3, 27, 1), GMT, BST), ] ) zi = tz.tzfile(zf, key="Europe/London") assert "Europe/London" in repr(zi) @pytest.mark.parametrize("zoneinfo_cache", ["fat"], indirect=True) @pytest.mark.parametrize("source", ["tzdata", "tzpath"]) def test_gettz_space_for_underscore(source, zoneinfo_cache): """Spaces in a key are tried as underscores, whichever source is used.""" if source == "tzdata": pytest.importorskip("tzdata") paths = () else: paths = (zoneinfo_cache[0],) with set_tzpath(paths, block_tzdata=(source != "tzdata")): tz.gettz.cache_clear() with_space = tz.gettz("America/New York") assert with_space is not None assert with_space.key == "America/New York" assert with_space == tz.gettz("America/New_York") #### # Key handling in gettz @pytest.mark.parametrize("zoneinfo_cache", ["fat"], indirect=True) @pytest.mark.parametrize("source", ["tzdata", "tzpath"]) def test_gettz_key_attribute_by_source(source, zoneinfo_cache): """The key is the string passed to gettz whichever source supplied it.""" if source == "tzdata": pytest.importorskip("tzdata") paths = () else: paths = (zoneinfo_cache[0],) with set_tzpath(paths, block_tzdata=(source != "tzdata")): tz.gettz.cache_clear() for key in ("America/New_York", "Europe/London"): zone = tz.gettz(key) assert isinstance(zone, tz.tzfile) assert zone.key == key @pytest.mark.parametrize("zoneinfo_cache", ["fat"], indirect=True) def test_gettz_absolute_path(zoneinfo_cache): """An absolute path to a TZif file is loaded directly and has no key.""" fpath = os.path.join(zoneinfo_cache[0], "America", "New_York") with set_tzpath((), block_tzdata=True): tz.gettz.cache_clear() zone = tz.gettz(fpath) assert isinstance(zone, tz.tzfile) assert zone.key is None assert repr(zone) == "tzfile(%r)" % fpath @pytest.mark.parametrize("zoneinfo_cache", ["fat"], indirect=True) def test_gettz_absolute_path_not_a_zone(zoneinfo_cache, tmp_path): """Absolute paths that are not TZif files return None.""" not_tzif = tmp_path / "not_a_zone" not_tzif.write_bytes(b"This is not a TZif file") with set_tzpath((), block_tzdata=True): tz.gettz.cache_clear() # A directory assert tz.gettz(os.path.join(zoneinfo_cache[0], "America")) is None # A file that does not exist assert tz.gettz(os.path.join(zoneinfo_cache[0], "Nope")) is None # A file that exists but is not a zone is an error, since an # absolute path is an explicit request for that file. with pytest.raises(ValueError): tz.gettz(str(not_tzif)) @pytest.mark.parametrize("zoneinfo_cache", ["fat"], indirect=True) @pytest.mark.parametrize( "key", [ "America/Nope", "America", # A directory on the search path "America/", "America/New_York\x00", "\x00", ], ) def test_gettz_tzpath_bad_keys(zoneinfo_cache, key): """Keys that do not name a zone on the search path return None.""" with set_tzpath((zoneinfo_cache[0],), block_tzdata=True): tz.gettz.cache_clear() assert tz.gettz(key) is None @pytest.mark.parametrize("zoneinfo_cache", ["fat"], indirect=True) def test_gettz_missing_search_path_entry(zoneinfo_cache, tmp_path): """Search path entries that do not exist are skipped, not errors.""" missing = str(tmp_path / "does_not_exist") with set_tzpath((missing, zoneinfo_cache[0]), block_tzdata=True): tz.gettz.cache_clear() assert tz.gettz("America/New_York") is not None assert tz.gettz("America/Nope") is None @pytest.mark.parametrize( "key", [ "America", # A directory "America/", "Fictional/Zone", "Fictional", "America/New_York\x00", # Not a valid path "America/../UTC", # Not a valid package name # Files in the tzdata package that are not TZif files "__init__.py", "America/__init__.py", "zone.tab", "tzdata.zi", "leapseconds", # Not encodable as a module or file name on some versions "Am" + chr(0xE9) + "rica/New_York", "America/" + chr(0xD800), chr(0xD800), ], ) def test_tzdata_bad_keys(key): """Keys that do not name a zone in tzdata return None, not an error.""" pytest.importorskip("tzdata") with set_tzpath(()): tz.gettz.cache_clear() assert tz.gettz(key) is None #### # available_iana_timezones def _make_fake_tzpath(root): """Populate a directory the way a zoneinfo installation is laid out.""" STD = ZoneOffset("STD", ZERO) DST = ZoneOffset("DST", ONE_H, ONE_H) tzif = construct_zone( [ZoneTransition(datetime(2010, 3, 14, 2), STD, DST)], "STD0DST,M3.2.0,M11.1.0", ).read() zones = [ "Fictional/Liliput", "Fictional/Blefuscu", "Fictional/Nested/Deep", "Fictional/right/NotExcluded", # Only top-level right/ is excluded "UTC", "posixrules", # Excluded by name "localtime", # Excluded by name "posix/Fictional/Liliput", # Excluded top-level directory "right/Fictional/Liliput", # Excluded top-level directory ] for zone in zones: path = os.path.join(root, *zone.split("/")) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "wb") as f: f.write(tzif) for not_zone in ["tzdata.zi", "Fictional/README", "leap-seconds.list"]: path = os.path.join(root, *not_zone.split("/")) with open(path, "wb") as f: f.write(b"This is not a TZif file\n") return { "Fictional/Liliput", "Fictional/Blefuscu", "Fictional/Nested/Deep", "Fictional/right/NotExcluded", "UTC", } def test_available_iana_timezones_tzpath_only(tmp_path): root = str(tmp_path) expected = _make_fake_tzpath(root) with set_tzpath((root,), block_tzdata=True): assert tz.available_iana_timezones() == expected def test_available_iana_timezones_missing_path(tmp_path): """Search path entries that do not exist are skipped.""" root = str(tmp_path / "zoneinfo") os.makedirs(root) expected = _make_fake_tzpath(root) missing = str(tmp_path / "missing") with set_tzpath((missing, root), block_tzdata=True): assert tz.available_iana_timezones() == expected def test_available_iana_timezones_empty(tmp_path): with set_tzpath((), block_tzdata=True): assert tz.available_iana_timezones() == set() def test_available_iana_timezones_with_tzdata(tmp_path): """Zones on the search path are merged with the ones from tzdata.""" tzdata = pytest.importorskip("tzdata") from dateutil._tzdata_impl import _load_tzdata_keys root = str(tmp_path) fake_zones = _make_fake_tzpath(root) tzdata_zones = set(_load_tzdata_keys()) with set_tzpath((root,)): zones = tz.available_iana_timezones() assert zones == fake_zones | tzdata_zones assert "posixrules" not in zones def test_available_iana_timezones_fresh_set(): """Each call returns a new set, so callers may mutate it.""" with set_tzpath((), block_tzdata=True): a = tz.available_iana_timezones() b = tz.available_iana_timezones() assert a is not b #### # TZPATH and reset_tzpath def test_tz_tzpath_tracks_reset(tmp_path): """dateutil.tz.TZPATH reflects reset_tzpath on every Python version.""" new_path = str(tmp_path) with set_tzpath((new_path,)): assert tz.TZPATH == (new_path,) assert "TZPATH" in dir(tz) assert tz.TZPATH != (new_path,) def test_invalid_tzpath_warning_is_zoneinfos(): import zoneinfo assert tz._tzpath.InvalidTZPathWarning is zoneinfo.InvalidTZPathWarning #### # Sub-minute offsets def _sub_minute_zone(): # Africa/Abidjan's LMT offset is -0:16:08; the file must contain the # exact value. LMT = ZoneOffset("LMT", timedelta(seconds=-968)) GMT = ZoneOffset("GMT", ZERO) return construct_zone( [ZoneTransition(datetime(1912, 1, 1), LMT, GMT)], "GMT0" ) def test_sub_minute_offset(): """Sub-minute offsets retain their exact value.""" zone = tz.tzfile(_sub_minute_zone()) dt = datetime(1900, 1, 1, tzinfo=zone) assert dt.utcoffset() == timedelta(seconds=-968) assert dt.tzname() == "LMT" assert datetime(2000, 1, 1, tzinfo=zone).utcoffset() == ZERO def test_sub_minute_offset_round_trip(): """Converting to and from UTC near a sub-minute transition round trips.""" # America/New_York's LMT offset is -4:56:02, so the switch to EST in 1883 # creates a fold whose boundaries move when the offset is rounded. LMT = ZoneOffset("LMT", timedelta(seconds=-17762)) EST = ZoneOffset("EST", timedelta(hours=-5)) zone = tz.tzfile( construct_zone( [ZoneTransition(datetime(1883, 11, 18, 12, 3, 58), LMT, EST)], "EST5", ) ) transition = datetime(1883, 11, 18, 17, tzinfo=tz.UTC) for seconds in range(-120, 121): dt_utc = transition + timedelta(seconds=seconds) assert dt_utc.astimezone(zone).astimezone(tz.UTC) == dt_utc @pytest.mark.parametrize("protocol", range(0, pickle.HIGHEST_PROTOCOL + 1)) def test_sub_minute_offset_pickle(protocol): """Pickling preserves sub-minute offsets.""" zone = tz.tzfile(_sub_minute_zone(), key="Africa/Abidjan") data = pickle.dumps(zone, protocol=protocol) # The pickled data carries the unrounded offsets from the file, so a # pickle made on a version that rounds still loads exactly elsewhere. _, args = zone.__reduce_ex__(protocol) _, _, _, zone_data = args utcoff = zone_data[2] assert -968 in utcoff unpickled = pickle.loads(data) assert unpickled == zone assert unpickled.key == "Africa/Abidjan" assert ( datetime(1900, 1, 1, tzinfo=unpickled).utcoffset() == datetime(1900, 1, 1, tzinfo=zone).utcoffset() ) class _DescribedTzfile(tz.tzfile): def __init__(self, fileobj, description, **kwargs): super().__init__(fileobj, **kwargs) self.description = description @pytest.mark.parametrize("protocol", range(0, pickle.HIGHEST_PROTOCOL + 1)) def test_pickle_subclass_attributes(protocol): """Pickling preserves attributes added by subclasses.""" STD = ZoneOffset("STD", -5 * ONE_H) DST = ZoneOffset("DST", -4 * ONE_H, ONE_H) transitions = [ ZoneTransition(datetime(2020, 3, 8, 2), STD, DST), ZoneTransition(datetime(2020, 11, 1, 2), DST, STD), ] zone = _DescribedTzfile( construct_zone(transitions, "STD5DST,M3.2.0,M11.1.0"), "Somewhere in the eastern US", key="Fictional/Eastern", ) unpickled = pickle.loads(pickle.dumps(zone, protocol=protocol)) assert type(unpickled) is _DescribedTzfile assert unpickled == zone assert unpickled.key == "Fictional/Eastern" assert unpickled.description == "Somewhere in the eastern US" assert ( datetime(2020, 7, 1, tzinfo=unpickled).utcoffset() == datetime(2020, 7, 1, tzinfo=zone).utcoffset() ) @pytest.mark.parametrize("key", ["America/New_York", "UTC", None]) def test_pickle_no_extra_state(key): """A plain tzfile is pickled entirely from its data. If this fails, an attribute set when loading a tzfile is missing from tzfile._UNPICKLE_ATTRS, so it is pickled twice. """ if key is None: zone = tz.tzfile(_sub_minute_zone()) else: zone = tz.gettz(key) assert isinstance(zone, tz.tzfile) assert len(zone.__reduce_ex__(pickle.HIGHEST_PROTOCOL)) == 2 #### # dst() inference # # TZif files only say whether each local time type is DST, so the amounts of # DST in these ZoneOffsets don't make it into the files; the expected dst() # values are given separately. @as_list def _dst_inference_cases(): def hm(hours, minutes=0, seconds=0): sign = -1 if hours < 0 else 1 return sign * timedelta( hours=abs(hours), minutes=minutes, seconds=seconds ) # The same local time type used for double summer time in one era and # for summer time in another, as with UTC+0 DST in Atlantic/Azores. STD_2 = ZoneOffset("-02", hm(-2)) SUMMER = ZoneOffset("-01", hm(-1), ONE_H) DOUBLE = ZoneOffset("+00", ZERO, 2 * ONE_H) STD_1 = ZoneOffset("-01", hm(-1)) yield pytest.param( [ ZoneTransition(datetime(1942, 4, 25), STD_2, SUMMER), ZoneTransition(datetime(1942, 8, 15), SUMMER, DOUBLE), ZoneTransition(datetime(1942, 9, 1), DOUBLE, SUMMER), ZoneTransition(datetime(1942, 10, 25), SUMMER, STD_2), ZoneTransition(datetime(1983, 9, 25), STD_2, STD_1), ZoneTransition(datetime(1984, 3, 25), STD_1, DOUBLE), ZoneTransition(datetime(1984, 9, 30), DOUBLE, STD_1), ], [ (datetime(1942, 7, 1), ONE_H), (datetime(1942, 8, 20), 2 * ONE_H), (datetime(1984, 7, 1), ONE_H), ], id="local_time_type_reused", ) # The standard offset changes when DST starts, as in # America/Bahia_Banderas in 2010. MST = ZoneOffset("MST", hm(-7)) MDT = ZoneOffset("MDT", hm(-6), ONE_H) CST = ZoneOffset("CST", hm(-6)) CDT = ZoneOffset("CDT", hm(-5), ONE_H) yield pytest.param( [ ZoneTransition(datetime(2009, 4, 5, 2), MST, MDT), ZoneTransition(datetime(2009, 10, 25, 2), MDT, MST), ZoneTransition(datetime(2010, 4, 4, 2), MST, CDT), ZoneTransition(datetime(2010, 10, 31, 2), CDT, CST), ZoneTransition(datetime(2011, 4, 3, 2), CST, CDT), ZoneTransition(datetime(2011, 10, 30, 2), CDT, CST), ], [ (datetime(2009, 7, 1), ONE_H), (datetime(2010, 7, 1), ONE_H), (datetime(2011, 7, 1), ONE_H), ], id="standard_offset_changes_with_dst", ) # The standard offset changes when DST ends, so the amounts implied by # the standard time before and after differ. Only the DST used nearby # tells Asia/Tehran in 1977 (1 hour) and Pacific/Rarotonga in 1978 (30 # minutes) apart. STD_A = ZoneOffset("STDA", hm(3, 30)) DST_A = ZoneOffset("DSTA", hm(4, 30), ONE_H) STD_B = ZoneOffset("STDB", hm(4)) DST_B = ZoneOffset("DSTB", hm(5), ONE_H) yield pytest.param( [ ZoneTransition(datetime(1976, 3, 21), STD_A, DST_A), ZoneTransition(datetime(1976, 10, 21), DST_A, STD_A), ZoneTransition(datetime(1977, 3, 21), STD_A, DST_A), ZoneTransition(datetime(1977, 10, 21), DST_A, STD_B), ZoneTransition(datetime(1978, 3, 21), STD_B, DST_B), ZoneTransition(datetime(1978, 10, 21), DST_B, STD_B), ], [(datetime(1977, 7, 1), ONE_H)], id="nearby_dst_one_hour", ) STD_A = ZoneOffset("-1030", hm(-10, 30)) DST_A = ZoneOffset("-0930", hm(-9, 30), timedelta(minutes=30)) STD_B = ZoneOffset("-10", hm(-10)) yield pytest.param( [ ZoneTransition(datetime(1978, 11, 12), STD_A, DST_A), ZoneTransition(datetime(1979, 3, 4), DST_A, STD_B), ZoneTransition(datetime(1979, 10, 28), STD_B, DST_A), ZoneTransition(datetime(1980, 3, 2), DST_A, STD_B), ], [ (datetime(1979, 1, 1), timedelta(minutes=30)), (datetime(1980, 1, 1), timedelta(minutes=30)), ], id="nearby_dst_half_hour", ) # When nothing else decides, prefer positive DST: in the 1942 occupation # zones, e.g. Europe/Kyiv, the standard time before gives -1:00 and the # one after gives +1:00. MSK = ZoneOffset("MSK", hm(3)) CEST = ZoneOffset("CEST", hm(2), ONE_H) CET = ZoneOffset("CET", hm(1)) yield pytest.param( [ ZoneTransition(datetime(1941, 9, 20), MSK, CEST), ZoneTransition(datetime(1942, 11, 2, 3), CEST, CET), ], [(datetime(1942, 7, 1), ONE_H)], id="prefer_positive", ) # A change from a mean time when DST ends, as in America/La_Paz in # 1932, implies an implausible amount of DST (0:27:24 here). CMT = ZoneOffset("CMT", hm(-4, 32, 36)) BST = ZoneOffset("BST", hm(-3, 32, 36), ONE_H) BOT = ZoneOffset("-04", hm(-4)) yield pytest.param( [ ZoneTransition(datetime(1931, 10, 15), CMT, BST), ZoneTransition(datetime(1932, 3, 21), BST, BOT), ], [(datetime(1932, 1, 1), ONE_H)], id="implausible_dst", ) @pytest.mark.parametrize("transitions, expected", _dst_inference_cases()) def test_dst_inference(transitions, expected): """dst() is inferred from the standard time around each DST period.""" zone = tz.tzfile(construct_zone(transitions)) for dt_utc, dst in expected: dt = dt_utc.replace(tzinfo=tz.UTC).astimezone(zone) assert dt.dst() == dst, dt_utc assert dt.replace(tzinfo=None).replace(tzinfo=zone).dst() == dst # The pickled data is the data from the file, so the inference gives the # same answers after a round trip assert pickle.loads(pickle.dumps(zone)) == zone #### # Thread safety def test_gettz_thread_safety(): """Concurrent gettz calls, with the cache being cleared underneath them.""" keys = ["America/New_York", "Europe/London", "Asia/Tokyo", "UTC"] expected = {key: tz.gettz(key) for key in keys} assert all(isinstance(v, tz.tzfile) for v in expected.values()) errors = [] n_iterations = 200 def worker(key): try: for i in range(n_iterations): zone = tz.gettz(key) if zone != expected[key]: raise AssertionError( "%s: %r != %r" % (key, zone, expected[key]) ) except Exception as e: # pragma: nocover errors.append(e) def clearer(): try: for i in range(n_iterations // 4): tz.gettz.cache_clear() except Exception as e: # pragma: nocover errors.append(e) threads = [threading.Thread(target=worker, args=(key,)) for key in keys * 2] threads.append(threading.Thread(target=clearer)) for t in threads: t.start() for t in threads: t.join() assert not errors python_dateutil-4.0.0/tests/test_tzpath_data.py0000644000000000000000000003042513615410400016731 0ustar00"""Properties that must hold for any valid IANA time zone data. Unlike the tests in ``test_tzfile.py``, which pin the data they use so that they can check specific historical transitions, these run against every key in whatever data is installed: the data on TZPATH (with tzdata blocked) and the tzdata package, via the ``tz_source`` fixture. In the ``tz`` CI jobs that is the master branch of the tz database, so these are the tests that catch the parser mishandling something new in the data. """ import calendar import os import zoneinfo from datetime import datetime, timedelta import pytest from dateutil import tz from dateutil.tz._tzfile import _TZStr pytestmark = pytest.mark.tzdata_properties UTC = tz.UTC EPOCH = datetime(1970, 1, 1, tzinfo=UTC) # The standard library's C implementation of zoneinfo is an independent # implementation of the same thing, so it is the reference. PAST_YEARS = (1850, 1900, 1945, 1970, 1990, 2000, 2020) FUTURE_YEARS = (2037, 2038, 2050, 2100, 2400, 9000) FIXED_INSTANTS = [ datetime(year, month, 1, tzinfo=UTC) for year in PAST_YEARS + FUTURE_YEARS for month in (1, 7) ] def _from_timestamp(ts): try: return EPOCH + timedelta(seconds=ts) except OverflowError: # e.g. the "big bang" transitions at -2**59 in fat files return None def _probe_instants(zone): """Instants (in UTC) around the interesting parts of a zone.""" instants = list(FIXED_INSTANTS) # Explicit transitions: the first few, and the last ones, which are # followed by the TZ string. transitions = list(zone._trans_utc) for ts in transitions[:3] + transitions[-10:]: for delta in (-1, 0, 1): instants.append(_from_timestamp(ts + delta)) # Transitions generated from the TZ string in the footer. if isinstance(zone._tz_after, _TZStr): std_offset = zone._tz_after.std.utcoff std_offset = std_offset.days * 86400 + std_offset.seconds for year in (2040, 2100): for local_ts in zone._tz_after.transitions(year): utc_ts = local_ts - std_offset for delta in (-7201, -3601, -1, 0, 1, 3599, 7199): instants.append(_from_timestamp(utc_ts + delta)) return [instant for instant in instants if instant is not None] def _keys(): keys = sorted(tz.available_iana_timezones()) assert keys return keys def test_every_key_loads(tz_source): """Every available key loads, from the source it was found in.""" tzpath = [os.path.join(path, "") for path in tz.TZPATH] for key in _keys(): zone = tz.gettz(key) assert isinstance(zone, tz.tzfile), key assert zone.key == key if tz_source == "tzpath": assert any(zone._filename.startswith(p) for p in tzpath), key def test_utc_round_trip(tz_source): """Converting from UTC to local time and back gives the same instant.""" for key in _keys(): zone = tz.gettz(key) for dt_utc in _probe_instants(zone): dt = dt_utc.astimezone(zone) assert dt.astimezone(UTC) == dt_utc, (key, dt_utc, dt) def test_ambiguous_and_imaginary(tz_source): """datetime_ambiguous and datetime_exists agree with the fold offsets.""" for key in _keys(): zone = tz.gettz(key) for dt_utc in _probe_instants(zone): local = dt_utc.astimezone(zone).replace(tzinfo=None) # Local times an hour either side are more likely to land in a # gap or a fold near a transition. for wall in ( local - timedelta(hours=1), local, local + timedelta(hours=1), ): dt = wall.replace(tzinfo=zone) offset_0 = tz.enfold(dt, fold=0).utcoffset() offset_1 = tz.enfold(dt, fold=1).utcoffset() case = (key, wall) assert tz.datetime_ambiguous(dt) == (offset_0 > offset_1), case assert tz.datetime_exists(dt) == (offset_0 >= offset_1), case def test_matches_zoneinfo(tz_source): """utcoffset, tzname and fromutc agree with the stdlib zoneinfo.""" # dateutil and zoneinfo share TZPATH, and the tz_source # fixture blocks (or allows) tzdata for both of them. # # This doesn't compare dst(), which zoneinfo infers differently, and gets # wrong for some zones (e.g. gh-85102); test_dst_matches_tzdata_zi checks # dst() against the source data instead. for key in _keys(): zone = tz.gettz(key) reference = zoneinfo.ZoneInfo.no_cache(key) for dt_utc in _probe_instants(zone): dt = dt_utc.astimezone(zone) dt_ref = dt_utc.astimezone(reference) if (dt.replace(tzinfo=None), dt.fold) != ( dt_ref.replace(tzinfo=None), dt_ref.fold, ): # zoneinfo gets some TZ strings wrong near the new year (e.g. # "0/0,J365/23" rules); only accept a difference where its # answer doesn't round trip and ours does. assert dt_ref.astimezone(UTC) != dt_utc, (key, dt_utc) assert dt.astimezone(UTC) == dt_utc, (key, dt_utc) wall = dt_utc.replace(tzinfo=None) for fold in (0, 1): dt = tz.enfold(wall.replace(tzinfo=zone), fold=fold) dt_ref = wall.replace(tzinfo=reference, fold=fold) if (dt.utcoffset(), dt.tzname()) != ( dt_ref.utcoffset(), dt_ref.tzname(), ): # As above: zoneinfo's offset has to be one that its own # fromutc contradicts, and ours has to be one ours agrees # with, so a difference in a real gap still fails. case = (key, wall, fold) ref_rt = dt_ref.astimezone(UTC).astimezone(reference) our_rt = dt.astimezone(UTC).astimezone(zone) assert ref_rt.replace(tzinfo=None) != wall, case assert our_rt.replace(tzinfo=None) == wall, case #### # dst() against the source data # # TZif files record the total UTC offset of each local time type and whether # it is DST, but not how much of the offset is DST, so dst() is inferred from # the neighboring transitions (see tzfile._utcoff_to_dstoff). The tzdata.zi # file installed alongside the TZif files (by the tz Makefile, and in the # tzdata package) has the standard offset for every period of every zone, so # away from the boundaries between periods, utcoffset() - dst() has to be the # standard offset from tzdata.zi. # # The inference gets this wrong in one place, in the 2024a, 2025b and 2026e # releases and the master branch, in the main, vanguard and rearguard forms and # as fat and slim files: from the liberation of Paris until September 1945, # France was on UTC+0 standard time with DST of 1 or 2 hours, but the TZif data # looks the same as the CET (UTC+1) standard time that followed, with DST of 1 # hour. Only failures outside of these periods fail the test. KNOWN_DST_INFERENCE_FAILURES = { "Europe/Paris": [ ( datetime(1944, 8, 25, tzinfo=UTC), datetime(1945, 9, 16, tzinfo=UTC), ), ], } def _is_known_dst_inference_failure(name, dt): return any( start <= dt < end for start, end in KNOWN_DST_INFERENCE_FAILURES.get(name, ()) ) _ZI_MONTHS = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ) _ZI_WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") # How far from a boundary between two periods of a zone (whose exact time # depends on rules that aren't evaluated here) a sample has to be. _ZI_BOUNDARY_MARGIN = 2 * 86400 def _zi_lookup(abbr, names): # tzdata.zi uses the shortest unambiguous abbreviations, e.g. "Ja", "Au" matches = [i for i, name in enumerate(names) if name.startswith(abbr)] assert len(matches) == 1, abbr return matches[0] def _zi_seconds(value): sign = -1 if value.startswith("-") else 1 parts = [int(part) for part in value.lstrip("-").split(":")] + [0, 0] return sign * (parts[0] * 3600 + parts[1] * 60 + parts[2]) def _zi_until(fields): """The approximate UTC timestamp of an UNTIL column.""" year = int(fields[0]) month = _zi_lookup(fields[1], _ZI_MONTHS) + 1 if len(fields) > 1 else 1 day = 1 if len(fields) > 2: day_spec = fields[2] days_in_month = calendar.monthrange(year, month)[1] if day_spec.startswith("last"): weekday = _zi_lookup(day_spec[4:], _ZI_WEEKDAYS) day = max( d for d in range(1, days_in_month + 1) if calendar.weekday(year, month, d) == weekday ) elif ">=" in day_spec or "<=" in day_spec: op = ">=" if ">=" in day_spec else "<=" name, first = day_spec.split(op) weekday = _zi_lookup(name, _ZI_WEEKDAYS) step = 1 if op == ">=" else -1 day = int(first) while calendar.weekday(year, month, day) != weekday: day += step else: day = int(day_spec) seconds = _zi_seconds(fields[3].rstrip("wsugz")) if len(fields) > 3 else 0 days = (datetime(year, month, 1) - datetime(1970, 1, 1)).days + day - 1 return days * 86400 + seconds def _parse_tzdata_zi(path): """Returns ({zone: [(stdoff, until), ...]}, {link: target}).""" zones = {} links = {} periods = None with open(path) as f: for line in f: fields = line.split("#", 1)[0].split() if not fields: continue if fields[0] == "Z": periods = zones.setdefault(fields[1], []) fields = fields[2:] elif fields[0] in ("R", "L"): if fields[0] == "L": links[fields[2]] = fields[1] periods = None continue # A zone line (without "Z ") or a continuation line: # STDOFF RULES FORMAT [UNTIL] until = _zi_until(fields[3:]) if len(fields) > 3 else None periods.append((_zi_seconds(fields[0]), until)) return zones, links def _find_tzdata_zi(tz_source): if tz_source == "tzdata": import tzdata candidates = [ os.path.join(os.path.dirname(tzdata.__file__), "zoneinfo") ] else: candidates = tz.TZPATH for directory in candidates: path = os.path.join(directory, "tzdata.zi") if os.path.exists(path): return path return None def test_dst_matches_tzdata_zi(tz_source): """utcoffset() - dst() is the standard offset given in tzdata.zi.""" path = _find_tzdata_zi(tz_source) if path is None: pytest.skip("No tzdata.zi alongside the TZif files") zones, links = _parse_tzdata_zi(path) failures = {} for key in _keys(): name = key while name in links: name = links[name] periods = zones.get(name) if periods is None: continue boundaries = [until for _, until in periods if until is not None] zone = tz.gettz(key) # Samples in the middle of the stretches between transitions, which # are where the answer is least ambiguous. transitions = list(zone._trans_utc) samples = [(a + b) // 2 for a, b in zip(transitions, transitions[1:])] samples += [ int((instant - EPOCH).total_seconds()) for instant in FIXED_INSTANTS ] for ts in samples: if any(abs(ts - b) < _ZI_BOUNDARY_MARGIN for b in boundaries): continue dt_utc = _from_timestamp(ts) if dt_utc is None: continue stdoff = next( stdoff for stdoff, until in periods if until is None or ts < until ) dt = dt_utc.astimezone(zone) std = dt.utcoffset() - dt.dst() if std.days * 86400 + std.seconds != stdoff: failures.setdefault(name, []).append(dt) unexpected = {} for name, dts in failures.items(): dts = [ dt for dt in dts if not _is_known_dst_inference_failure(name, dt) ] if dts: unexpected[name] = dts[:3] assert not unexpected python_dateutil-4.0.0/tests/test_utils.py0000644000000000000000000000270113615410400015562 0ustar00from datetime import datetime, timedelta import pytest from freezegun import freeze_time from dateutil import tz, utils from dateutil.tz import UTC from dateutil.utils import within_delta @pytest.fixture def NYC(): zone = tz.gettz("America/New_York") assert zone is not None return zone @freeze_time(datetime(2014, 12, 15, 1, 21, 33, 4003)) def test_utils_today(): assert utils.today() == datetime(2014, 12, 15, 0, 0, 0) @freeze_time(datetime(2014, 12, 15, 12), tz_offset=5) def test_utils_today_tz_info(NYC): assert utils.today(NYC) == datetime(2014, 12, 15, 0, 0, 0, tzinfo=NYC) @freeze_time(datetime(2014, 12, 15, 23), tz_offset=5) def test_utils_today_tz_info_different_day(): assert utils.today(UTC) == datetime(2014, 12, 16, 0, 0, 0, tzinfo=UTC) def test_utils_default_tz_info_naive(NYC): dt = datetime(2014, 9, 14, 9, 30) assert utils.default_tzinfo(dt, NYC).tzinfo is NYC def test_utils_default_tz_info_aware(NYC): dt = datetime(2014, 9, 14, 9, 30, tzinfo=UTC) assert utils.default_tzinfo(dt, NYC).tzinfo is UTC def test_utils_within_delta(): d1 = datetime(2016, 1, 1, 12, 14, 1, 9) d2 = d1.replace(microsecond=15) assert within_delta(d1, d2, timedelta(seconds=1)) assert not within_delta(d1, d2, timedelta(microseconds=1)) def test_utils_within_delta_with_negative_delta(): d1 = datetime(2016, 1, 1) d2 = datetime(2015, 12, 31) assert within_delta(d2, d1, timedelta(days=-1)) python_dateutil-4.0.0/tests/test_zoneinfo.py0000644000000000000000000001072313615410400016254 0ustar00"""Tests for the deprecated ``dateutil.zoneinfo`` shim.""" import io import json import tarfile import warnings from datetime import datetime import pytest from dateutil import tz from .test_tzfile import ONE_H, ZERO, ZoneOffset, ZoneTransition, construct_zone with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) from dateutil import zoneinfo def _legacy_tarball(with_metadata=True): """Builds a tarball in the format ``dateutil`` used to ship.""" STD = ZoneOffset("STD", ZERO) DST = ZoneOffset("DST", ONE_H, ONE_H) tzif = construct_zone( [ZoneTransition(datetime(2010, 3, 14, 2), STD, DST)], "STD0DST,M3.2.0,M11.1.0", ).read() buf = io.BytesIO() with tarfile.open(fileobj=buf, mode="w:gz") as tf: info = tarfile.TarInfo("Fictional/Liliput") info.size = len(tzif) tf.addfile(info, io.BytesIO(tzif)) link = tarfile.TarInfo("Fictional/Link") link.type = tarfile.LNKTYPE link.linkname = "Fictional/Liliput" tf.addfile(link) if with_metadata: metadata = json.dumps( {"metadata_version": "2.0", "tzversion": "1999z"} ).encode("utf-8") info = tarfile.TarInfo(zoneinfo.METADATA_FN) info.size = len(metadata) tf.addfile(info, io.BytesIO(metadata)) buf.seek(0) return buf def test_zoneinfofile_eager_load(): tzdata = pytest.importorskip("tzdata") from dateutil._tzdata_impl import _load_tzdata_keys zif = zoneinfo.ZoneInfoFile() assert set(zif.zones) == set(_load_tzdata_keys()) assert zif.metadata == { "metadata_version": "3.0", "tzversion": tzdata.IANA_VERSION, } NYC = zif.get("America/New_York") assert isinstance(NYC, tz.tzfile) assert NYC.key == "America/New_York" assert datetime(2020, 7, 1, tzinfo=NYC).tzname() == "EDT" assert datetime(2020, 1, 1, tzinfo=NYC).tzname() == "EST" assert zif.get("Fictional/Liliput") is None assert zif.get("Fictional/Liliput", "default") == "default" def test_zoneinfofile_no_tzdata(block_tzdata): with pytest.raises(ImportError, match="tzdata"): zoneinfo.ZoneInfoFile() @pytest.mark.parametrize("with_metadata", [True, False]) def test_zoneinfofile_legacy_stream(with_metadata): zif = zoneinfo.ZoneInfoFile(_legacy_tarball(with_metadata)) assert set(zif.zones) == {"Fictional/Liliput", "Fictional/Link"} assert zif.zones["Fictional/Link"] is zif.zones["Fictional/Liliput"] liliput = zif.get("Fictional/Liliput") assert isinstance(liliput, tz.tzfile) assert datetime(2010, 7, 1, tzinfo=liliput).tzname() == "DST" if with_metadata: assert zif.metadata == {"metadata_version": "2.0", "tzversion": "1999z"} else: assert zif.metadata is None def test_legacy_gettz(): pytest.importorskip("tzdata") with pytest.warns(DeprecationWarning): NYC = zoneinfo.gettz("America/New_York") assert isinstance(NYC, tz.tzfile) assert NYC.key == "America/New_York" with pytest.warns(DeprecationWarning): assert zoneinfo.gettz("Fictional/Liliput") is None #### # rebuild with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) from dateutil.zoneinfo import rebuild as zoneinfo_rebuild def test_rebuild_is_an_error_by_default(tmp_path): target = tmp_path / "dateutil-zoneinfo.tar.gz" with warnings.catch_warnings(): warnings.resetwarnings() with pytest.raises(zoneinfo_rebuild.RebuildDeprecationWarning): zoneinfo_rebuild.rebuild(str(target)) assert not target.exists() def test_rebuild_filter_can_be_overridden(tmp_path): target = tmp_path / "dateutil-zoneinfo.tar.gz" with warnings.catch_warnings(record=True) as record: warnings.resetwarnings() warnings.simplefilter( "always", category=zoneinfo_rebuild.RebuildDeprecationWarning ) assert zoneinfo_rebuild.rebuild(str(target)) is None assert len(record) == 1 assert record[0].category is zoneinfo_rebuild.RebuildDeprecationWarning assert record[0].filename == __file__.replace(".pyc", ".py") assert not target.exists() def test_rebuild_can_be_ignored(): with warnings.catch_warnings(): warnings.resetwarnings() warnings.filterwarnings( "ignore", category=zoneinfo_rebuild.RebuildDeprecationWarning ) assert zoneinfo_rebuild.rebuild("unused.tar.gz") is None python_dateutil-4.0.0/tests/property/test_isoparse_prop.py0000644000000000000000000000345213615410400021177 0ustar00from datetime import datetime import pytest from hypothesis import assume, example, given, settings from hypothesis import strategies as st from dateutil import tz from dateutil.parser import isoparse # Strategies ZONES = [ tz.gettz(zname) for zname in ( "America/New_York", "America/Los_Angeles", "Australia/Sydney", "Europe/London", ) ] # A missing zone must not silently turn into a naive datetime. assert None not in ZONES TIME_ZONE_STRATEGY = st.sampled_from([None, tz.UTC] + ZONES) ASCII_STRATEGY = st.characters(max_codepoint=127) @pytest.mark.isoparser @settings(deadline=3000) @given(dt=st.datetimes(timezones=TIME_ZONE_STRATEGY), sep=ASCII_STRATEGY) # Ambiguous in US/Eastern: the first 01:00 (EDT) and the second (EST) @example(dt=datetime(2020, 11, 1, 1, tzinfo=tz.gettz("US/Eastern")), sep="T") @example( dt=tz.enfold(datetime(2020, 11, 1, 1, tzinfo=tz.gettz("US/Eastern")), 1), sep="T", ) def test_timespec_auto(dt, sep): if dt.tzinfo is not None: # Assume offset has no sub-second components assume(dt.utcoffset().total_seconds() % 60 == 0) dtstr = dt.isoformat(sep=sep) dt_rt = isoparse(dtstr) # The round trip preserves the wall time and the offset. assert dt_rt.replace(tzinfo=None) == dt.replace(tzinfo=None) assert dt_rt.utcoffset() == dt.utcoffset() # According to PEP 495, if the value of fold would change the return value # of utcoffset(), comparisons with the datetime always return false, so we # must handle the case of ambiguous and imaginary datetimes here for the # property to remain valid. if ( dt.tzinfo is None or tz.enfold(dt, fold=0).utcoffset() == tz.enfold(dt, fold=1).utcoffset() ): assert dt_rt == dt else: assert dt_rt != dt python_dateutil-4.0.0/tests/property/test_parser_prop.py0000644000000000000000000000104613615410400020643 0ustar00from hypothesis.strategies import integers from hypothesis import given import pytest from dateutil.parser import parserinfo @pytest.mark.parserinfo @given(integers(min_value=100, max_value=9999)) def test_convertyear(n): assert n == parserinfo().convertyear(n) @pytest.mark.parserinfo @given(integers(min_value=-50, max_value=49)) def test_convertyear_no_specified_century(n): p = parserinfo() new_year = p._year + n result = p.convertyear(new_year % 100, century_specified=False) assert result == new_year python_dateutil-4.0.0/tests/property/test_rrule_prop.py0000644000000000000000000000715513615410400020507 0ustar00import copy import itertools import pickle from datetime import datetime import pytest from hypothesis import given from hypothesis import strategies as st from dateutil import tz from dateutil.rrule import DAILY, SECONDLY, YEARLY, rrule, rruleset @st.composite def recurrence_options(draw): """Finite rules with varied frequencies, weekdays, intervals and timezones.""" return dict( freq=draw(st.integers(min_value=YEARLY, max_value=SECONDLY)), dtstart=draw( st.datetimes( min_value=datetime(2000, 1, 1), max_value=datetime(2030, 12, 31), timezones=st.sampled_from( [None, tz.UTC, tz.tzoffset(None, 3600)] ), ) ), count=draw(st.integers(min_value=0, max_value=25)), interval=draw(st.integers(min_value=1, max_value=5)), byweekday=draw( st.lists( st.integers(min_value=0, max_value=6), min_size=1, max_size=7, unique=True, ) ), ) def _pickle_roundtrip(value, protocol): serialized = pickle.dumps(value, protocol) return pickle.loads(serialized) @pytest.mark.rrule @pytest.mark.parametrize( "cache_state", ["disabled", "empty", "partial", "complete"] ) @pytest.mark.parametrize("operation", ["pickle", "deepcopy"]) @given( options=recurrence_options(), protocol=st.integers(2, pickle.HIGHEST_PROTOCOL), ) def test_rrule_roundtrip(options, protocol, cache_state, operation): expected = list(rrule(**options)) original = rrule(cache=cache_state != "disabled", **options) iterator = None prefix = [] if cache_state == "partial": iterator = iter(original) prefix = list(itertools.islice(iterator, 1)) elif cache_state == "complete": assert list(original) == expected restored = ( _pickle_roundtrip(original, protocol) if operation == "pickle" else copy.deepcopy(original) ) assert list(restored) == expected assert restored.count() == len(expected) assert str(restored) == str(original) if iterator is not None: assert prefix + list(iterator) == expected assert list(original) == expected @pytest.mark.rruleset @pytest.mark.parametrize( "cache_state", ["disabled", "empty", "partial", "complete"] ) @pytest.mark.parametrize("operation", ["pickle", "deepcopy"]) @given( options=recurrence_options(), protocol=st.integers(2, pickle.HIGHEST_PROTOCOL), ) def test_rruleset_roundtrip(options, protocol, cache_state, operation): cache = cache_state != "disabled" original = rruleset(cache=cache) original.rrule(rrule(cache=cache, **options)) start = options["dtstart"].replace(microsecond=0) original.rdate(start) # Mix included rules/dates with exclusions, including nested cached rules. original.exdate(start) original.exrule(rrule(DAILY, dtstart=start, count=2, cache=cache)) expected = sorted( set(rrule(**options)) - set(rrule(DAILY, dtstart=start, count=2)) ) iterator = None prefix = [] if cache_state == "partial": iterator = iter(original) prefix = list(itertools.islice(iterator, 1)) elif cache_state == "complete": assert list(original) == expected restored = ( _pickle_roundtrip(original, protocol) if operation == "pickle" else copy.deepcopy(original) ) assert list(restored) == expected assert restored.count() == len(expected) if iterator is not None: assert prefix + list(iterator) == expected assert list(original) == expected python_dateutil-4.0.0/tests/property/test_tz_prop.py0000644000000000000000000000703713615410400020012 0ustar00from datetime import datetime, timedelta import pytest from hypothesis import example, given from hypothesis import strategies as st from dateutil import tz from tests._common import tz_source_context, tz_source_skip_reason # Bounds of a signed 32-bit time_t, as naive *UTC* datetimes. They are naive # because st.datetimes() requires naive bounds; the strategy attaches tz.UTC # to them, so they must be computed in UTC and not with fromtimestamp(), # which returns local time and would shift them by the process time zone. EPOCH = datetime(1970, 1, 1) EPOCHALYPSE = EPOCH + timedelta(seconds=2**31 - 1) NEGATIVE_EPOCHALYPSE = EPOCH - timedelta(seconds=2**31) @pytest.mark.gettz def test_key_property(tz_source): """Every available key loads, and keeps the key it was loaded with.""" keys = sorted(tz.available_iana_timezones()) assert keys for key in keys: tzi = tz.gettz(key) assert isinstance(tzi, tz.tzfile), key assert tzi.key == key @pytest.mark.gettz # The C library reads the data on TZPATH, so that's what gettz must use too. @pytest.mark.skipif( tz_source_skip_reason("tzpath") is not None, reason="No time zone data on TZPATH", ) @pytest.mark.parametrize("gettz_arg", [None, ""]) # TODO: Remove bounds when GH #590 is resolved @given( dt=st.datetimes( min_value=NEGATIVE_EPOCHALYPSE, max_value=EPOCHALYPSE, timezones=st.just(tz.UTC), ) ) # Explicit examples are UTC-aware like the generated values, so that they go # through the same code path (a naive dt would be interpreted as local time, # which puts a fixed "very old" example inside or outside the GH #590 bound # depending on the process time zone). # 01:15 in America/New_York on a fall-back day, i.e. ambiguous local time. @example(dt=datetime(2005, 10, 30, 5, 15, tzinfo=tz.UTC)) # 01:00 in America/New_York on a fall-back day: CI's falsifying example. @example(dt=datetime(2015, 11, 1, 5, 0, tzinfo=tz.UTC)) # Very old: the 32-bit floor itself. CI's falsifying example was 5 hours # earlier, which is outside the bound (the miscomputed local-time bound let # it through); that value fails by design (GH #590), so the regression check # is the edge of the corrected bound. @example(dt=NEGATIVE_EPOCHALYPSE.replace(tzinfo=tz.UTC)) @example(dt=EPOCHALYPSE.replace(tzinfo=tz.UTC)) def test_gettz_returns_local(gettz_arg, dt): with tz_source_context("tzpath"): act_tz = tz.gettz(gettz_arg) if isinstance(act_tz, tz.tzlocal): return dt_act = dt.astimezone(act_tz) dt_exp = dt.astimezone() assert dt_act.astimezone(tz.UTC) == dt_exp.astimezone(tz.UTC) assert dt_act.tzname() == dt_exp.tzname() assert dt_act.utcoffset() == dt_exp.utcoffset() # According to PEP 495, if the value of fold would change the return value # of utcoffset(), comparisons with the datetime always return false, so we # must handle the case of ambiguous and imaginary datetimes here for the # property to remain valid. if ( tz.enfold(dt_act, fold=0).utcoffset() == tz.enfold(dt_act, fold=1).utcoffset() ): assert dt_act == dt_exp else: # Check that the system time zone also considers the local wall time # ambiguous. This must be done on the naive wall time: fold has no # effect on the UTC-aware dt, and dt_exp carries a fixed offset. wall = dt_exp.replace(tzinfo=None) assert ( tz.enfold(wall, fold=0).astimezone().utcoffset() != tz.enfold(wall, fold=1).astimezone().utcoffset() ) assert dt_act != dt_exp python_dateutil-4.0.0/tests/resources/__init__.py0000644000000000000000000000000013615410400017122 0ustar00python_dateutil-4.0.0/tests/resources/liliput_tzif0000644000000000000000000000437213615410400017472 0ustar00TZif2 � €› `›ÕÚðœÙ®��¤µ�ž¹��Ÿ„—�È q�ÌçKÍ©�΢CÏ’4Ђ%ÑrѶ–ÒX¾€Ò¡OÓc�ÔK#�Õ9Ñ Õgç�Õ¨sÖ)´×,Ø –ÙÁ�ÙéxMD3ú�#ë�Ü�Í�ó¾�ã¯�Ó �Ñ�¼½¬®œŸŒ�|� lr!\c"LT#†A�?›�@f#�A„9BF�CdD%ç�ECýFÉ�G#ßGîæIÁIÎÈJã£K®ªLÌ¿�MŽŒN¬¡�OnnPŒƒ�QWŠ�Rle�S7l�TLG�UN�V,)�V÷0�XFX×�Yõ(Z¶ô�[Õ \ ]´ì^ó_”Î`_Õa}ê�b?·c]Ì�d™e=®�fµ�g��gè—�hýr�iÈy�jÝT�k¨[�lÆqmˆ=�n¦Soh�p†5qQ<rfs1tEùuv/�vðâx÷�xÐÄyîÙ�z°¦{λ�|™Â�}®��~y¤�Ž� ˆ    *0 *0   LMTCESTCETCEMTTZif2 � ÿÿÿÿo¢aøÿÿÿÿ› `ÿÿÿÿ›ÕÚðÿÿÿÿœÙ®�ÿÿÿÿ�¤µ�ÿÿÿÿž¹��ÿÿÿÿŸ„—�ÿÿÿÿÈ q�ÿÿÿÿÌçKÿÿÿÿÍ©�ÿÿÿÿ΢CÿÿÿÿÏ’4ÿÿÿÿЂ%ÿÿÿÿÑrÿÿÿÿѶ–ÿÿÿÿÒX¾€ÿÿÿÿÒ¡OÿÿÿÿÓc�ÿÿÿÿÔK#�ÿÿÿÿÕ9Ñ ÿÿÿÿÕgç�ÿÿÿÿÕ¨sÿÿÿÿÖ)´ÿÿÿÿ×,ÿÿÿÿØ –ÿÿÿÿÙÁ�ÿÿÿÿÙéxMD3ú�#ë�Ü�Í�ó¾�ã¯�Ó �Ñ�¼½¬®œŸŒ�|� lr!\c"LT#†A�?›�@f#�A„9BF�CdD%ç�ECýFÉ�G#ßGîæIÁIÎÈJã£K®ªLÌ¿�MŽŒN¬¡�OnnPŒƒ�QWŠ�Rle�S7l�TLG�UN�V,)�V÷0�XFX×�Yõ(Z¶ô�[Õ \ ]´ì^ó_”Î`_Õa}ê�b?·c]Ì�d™e=®�fµ�g��gè—�hýr�iÈy�jÝT�k¨[�lÆqmˆ=�n¦Soh�p†5qQ<rfs1tEùuv/�vðâx÷�xÐÄyîÙ�z°¦{λ�|™Â�}®��~y¤�Ž� ˆ    *0 *0   LMTCESTCETCEMT CET-1CEST,M3.5.0,M10.5.0/3 python_dateutil-4.0.0/tests/resources/update_tzif.py0000644000000000000000000001656513615410400017730 0ustar00# /// script # dependencies = [ # "requests", # ] # /// from __future__ import annotations import asyncio import base64 import gzip import json import logging import os import pathlib import shutil import struct import subprocess import tempfile import urllib.parse from typing import Final IANA_LATEST_LOCATION: Final[str] = ( "https://www.iana.org/time-zones/repository/tzdb-latest.tar.lz" ) SOURCE: Final[str] = "https://data.iana.org/time-zones/releases" DATA_DIR: Final[pathlib.Path] = pathlib.Path("tests/resources/data") def _is_tzif(fpath: pathlib.Path) -> bool: if fpath.is_dir(): return False with open(fpath, "rb") as f: magic = f.read(4) return magic == b"TZif" def _parse_filename_from_url(url: str) -> str: parsed_url = urllib.parse.urlparse(url) filename = parsed_url.path.rsplit("/", 1)[-1] return filename async def download_tzdb( working_dir: pathlib.Path, url: str = IANA_LATEST_LOCATION, ) -> pathlib.Path: """Download the tzdata and tzcode tarballs.""" # Imported here so that the tests can import this module without requests import requests filename = _parse_filename_from_url(url) r = requests.get(url, allow_redirects=True, stream=True) download_location = working_dir / filename logging.info( "Downloaded %s from %s to %s", filename, url, download_location ) with open(download_location, "wb") as f: f.write(r.raw.read()) return download_location async def unpack_tzdb_tarball( download_location: pathlib.Path, output_dir: pathlib.Path | None = None, cwd: pathlib.Path | None = None, ) -> pathlib.Path: logging.info("Unpacking %s to %s", download_location, output_dir) if cwd is None: cwd = pathlib.Path.cwd() if output_dir is None: output_dir = cwd / "tzdb" output_dir.mkdir() await asyncio.to_thread( subprocess.run, [ "tar", "--lzip", "-xf", os.fspath(download_location.absolute()), "-C", os.fspath(output_dir), ], cwd=cwd, check=True, ) # The tzdb tarball has for some reason a top-level directory called # tzdb-..., which is annoying to deal with. We will delete that and # unpack its contents into `output_dir` for i, subdir in list(enumerate(output_dir.glob("tzdb-*"))): if i >= 1: raise ValueError("TZDB directory contains more than one subdir") for p in subdir.iterdir(): p.rename(output_dir / p.name) subdir.rmdir() return output_dir async def _file_to_v1(tzif_file: pathlib.Path, out_path: pathlib.Path) -> None: # Make sure that the parents exist out_path.parent.mkdir(parents=True, exist_ok=True) # Ensure that this is a valid TZif file contents = tzif_file.read_bytes() if contents[0:4] != b"TZif": raise ValueError(f"Invalid TZif data found! {tzif_file}") # Version 1 files have a NUL byte in place of the version number version_byte = contents[4:5] version = 1 if version_byte == b"\x00" else int(version_byte) header_start = 4 + 16 header_end = header_start + 24 # 6l == 24 bytes if version < 2: logging.warning( "Version 1 file found, no conversion necessary (%s)", tzif_file ) shutil.copyfile(tzif_file, out_path) return isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt = struct.unpack( ">6l", contents[header_start:header_end] ) file_size = ( timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + isstdcnt + isutcnt ) file_size += header_end out = b"TZif" + b"\x00" + contents[5:file_size] if contents[file_size : (file_size + 4)] != b"TZif": raise ValueError( f"Version 2 file not truncated at Version 2 header: {tzif_file}" ) out_path.write_bytes(out) async def tzif_files_to_v1( input_base_path: pathlib.Path, output_base_path: pathlib.Path ) -> None: tasks = [] for tzif_in_file in filter(_is_tzif, input_base_path.rglob("*")): tzif_v1_file = output_base_path / tzif_in_file.relative_to( input_base_path ) tasks.append( asyncio.create_task(_file_to_v1(tzif_in_file, tzif_v1_file)) ) await asyncio.gather(*tasks) async def make_tzdb_install( install_dir: pathlib.Path, cwd: pathlib.Path, slim: bool ) -> None: cmd = ["make", f"DESTDIR={os.fspath(install_dir)}"] if slim: cmd.append("ZFLAGS=-b slim") else: cmd.append("ZFLAGS=-b fat") cmd.append("install") await asyncio.to_thread( subprocess.run, cmd, check=True, cwd=cwd, ) def file_to_text(tzif_file: pathlib.Path) -> str: """Compress the file with gzip and base64 encode.""" tzif_data = tzif_file.read_bytes() compressed_data = gzip.compress(tzif_data) b64_data = base64.b64encode(compressed_data).decode("utf-8") return b64_data def zonefile_to_json( data_root: pathlib.Path, json_outfile: pathlib.Path, keys: frozenset[str] ) -> None: out_data = {} for dirpath, dirnames, filenames in data_root.walk(): for file in filenames: filepath = dirpath / file tzkey = str(filepath.relative_to(data_root)) if tzkey not in keys: continue out_data[tzkey] = file_to_text(dirpath / file) json_outfile.write_text(json.dumps(out_data, sort_keys=True, indent=2)) def write_metadata(json_outfile: pathlib.Path, tzdb_dir: pathlib.Path) -> None: """Record which tzdb release the data files were generated from.""" version = (tzdb_dir / "version").read_text().strip() logging.info("Generated data from tzdb version %s", version) metadata = {"tzdata_version": version} json_outfile.write_text( json.dumps(metadata, sort_keys=True, indent=2) + "\n" ) def read_required_keys(loc: pathlib.Path) -> frozenset[str]: json_str = loc.read_text() return frozenset(json.loads(json_str)) async def main() -> None: required_keys = read_required_keys(DATA_DIR / "keys.json") with tempfile.TemporaryDirectory() as td: tdp = pathlib.Path(td) download_location = await download_tzdb(working_dir=tdp) tzdata_dir = tdp / "tzdb" V1_OUT = tdp / "v1" V2P_OUT = tdp / "v2p_fat" V2P_OUT_SLIM = tdp / "v2p_slim" await unpack_tzdb_tarball( download_location, cwd=tdp, output_dir=tzdata_dir ) v2p_fat_future = make_tzdb_install(V2P_OUT, cwd=tzdata_dir, slim=False) v2p_slim_future = make_tzdb_install( V2P_OUT_SLIM, cwd=tzdata_dir, slim=True ) V2P_ZONEINFO = V2P_OUT / "usr/share/zoneinfo" V2P_SLIM_ZONEINFO = V2P_OUT_SLIM / "usr/share/zoneinfo" await v2p_fat_future v1_future = tzif_files_to_v1(V2P_OUT / "usr/share/zoneinfo", V1_OUT) await asyncio.gather(v2p_slim_future, v1_future) zonefile_to_json( V1_OUT, DATA_DIR / "zoneinfo_v1.json", keys=required_keys ) zonefile_to_json( V2P_ZONEINFO, DATA_DIR / "zoneinfo_fat.json", keys=required_keys ) zonefile_to_json( V2P_SLIM_ZONEINFO, DATA_DIR / "zoneinfo_slim.json", keys=required_keys, ) write_metadata(DATA_DIR / "metadata.json", tzdata_dir) if __name__ == "__main__": asyncio.run(main()) python_dateutil-4.0.0/tests/resources/data/__init__.py0000644000000000000000000000000013615410400020033 0ustar00python_dateutil-4.0.0/tests/resources/data/keys.json0000644000000000000000000000040013615410400017574 0ustar00[ "Africa/Abidjan", "Africa/Casablanca", "America/Los_Angeles", "America/New_York", "America/Santiago", "Australia/Sydney", "Asia/Tokyo", "Europe/Dublin", "Europe/Lisbon", "Europe/London", "Pacific/Kiritimati" ] python_dateutil-4.0.0/tests/resources/data/metadata.json0000644000000000000000000000004013615410400020401 0ustar00{ "tzdata_version": "2025b" } python_dateutil-4.0.0/tests/resources/data/zoneinfo_fat.json0000644000000000000000000003747113615410400021324 0ustar00{ "Africa/Abidjan": "H4sIAPygLGgC/wuJykwzYsALGIGYCYg5Jj2b5MH4//8fC6gEi49vCIM7EIeQYMh/IMBpEBeQMOACAG2uGIiUAAAA", "Africa/Casablanca": "H4sIAPygLGgC/72VfUzUdRzHDwVHgno1IkervhmkSQ5xPkQl5GClBgjegQciGjMe4hjn5YAMx10qMkGSOSTlRt9EYoACM5KnEh94NEPlxoBEx0yjraiD6dBho+/781n/VCv/qfvt9rr356/37V5v0MemJC7T/ONrq3q7qLf7kcgHts5pD0uX4aSpa2jM0vfZMsf1FSc0139Z6JjyMb8xdeFXk2vqXotrZ5rD7Ud3jfs7bznm9ARZ5hZOmObZIy3aheUmr8bPNc/OT3esXfODZW3rAtP6F7w06w/2m94ePmcJ3XLHFFbSZAlfXuDYYJMywrVVRvgfExFJlTIy+yMZOfiN3OhSJjca35e6VbukrvZ5qRt+U+hDo2TUU3EyKntERNU4y+iXV8noyUC5SbdfbrKeFIYn9cIwIGSMuCtjDDoZc2+liG2cIWMnbWKzzzm5uX++iOsNlnEPk0V8ab2Mt8+T28wGsU1my4SgDpGQ6S22exrl9pAi8e6Yh0h8+hWZ1GIVSeMjIqVokUxpCxOpSVdFavFdmbZitUgz2kS6222Z/upjwjQUKXdo66W57oEw33xG7syVcmdDh8jQz5EZ+UaZtfhLkWUYkh/cXyB2+VnFh709MnvWIrm7YofYbS+WOeabIqd6tZjh9Kdn5l8uf/PMdH7EZ3r6/m381nO1Ts70o7vis4Y+O7mGhuk1vkv91XupRv/vwnT8Icy0ekEaEOKAkIeoBAIhEQiRiEomEEIRlVRUSIlFVHKBEAwvSAZCNPoGSjYQwoGQDoR4eEE+EAISlYQgRCQqGUEICUJKEGKCkBOEoCAkJSpRiUpWEMISlbQgxCUqeUEITFQSE5XIIGQGITRRSU1UYoOQm6gEByE5UYkOQnaiEh6E9EQlPlHJD2IARDUCEEMgqjGAGARRjQLEMIhqHCAGQlQjATEUohoLiMEQ1WhADAfEeEAMiDjO3w9DIqoxgRgUsZj7Y1hEI/fFwIhqZCCGBmJsIAZHVKMDMTxiA/fEAIn53BNDJKoxghgkiFGCGCaIcYIYKFGNFMRQidXc07puH92tmdWU94glzHDuuXeMfdnnzT1z29fQPXcikXJeUS3lvB7ueSA5mu4HPuWeBYG/0b0gjXsWur9HuTCYe378/RN0P/T4SspFzc3MUe55eP+LlA+f5Z7FW3rpXpw/QbnE9zXKJQnc86jTLbofDeCexwYP0L10Fve0VUxStt3gnmXZ7HtZ9UXKUsd+Syv3PC6+oHzcwD3LJ2PpfsInh3JFexfliofcs7I0ne6VfdyzyuxJ9yrJPWuC9lCuyeCepzx96X4qZAPl2p/7iHVe3LO+JYhy/Tj3PH1olO6n29woN8TzjhqKueeZ5VN0P2Pknk1u5XRvCuCezUNayi1a7tla10j31hvDlL/O3cps4J5tusuU2/K55/nF/HfhvOETyhcmRyhf9OOe7b15dO9w4Z6dFX5077Rzz26zjXJ3Ffe8tC6E7pcykylffu4nZjj3/HbMQLnXm3teadfQ/cqEN+VrRWmUr3VzT3uyB93tRwIo9wd+xTRyzwH3lygPBHPPwVtX6T6kvUf5u+Ys5ij3HM69Q3n4bMh//c/t/3ke/V/o7NfVp8Al/rN/B9RLLRR9CQAA", "America/Los_Angeles": "H4sIAPygLGgC/+3Ve0zVZRzHcUAUQdEnEyVCe1ITQUBAUbyUedsBFVFBEjO8JDBMQ4VQy5AWZdaML5mXbvRo1nJlaM5mWYS2XK1ZBs15i8hSmYoXtMRLnJ73o//1V3+29Zz9fq+zc85/v533J2NGfm6Czz9Ou9sX57Pb77uW2lvle8nm7T0hYp6PMptevyrfrQ4ztb2vLKqd01cdai2aebh0mxxt/UqO1Yg6Xv+u/Lz1Q6mvXiW/rH5ZGirz5df8RXKiZIL8ljJVfs+OkZORg+SUZ7w63WWKaoyIVo3NA9WZgE7qTG2IOnvqojq346pq2l+rzlccUReqzsvFxXvUpfKD0rxyr1wu+FiuzHpH/kh7Vf4c+ZxcHVAsLf02q2udp8v19mXqesuz+kZjrrp5OEf/9U2yat3t0d73o5TPxkjt+0JH5besg26zuJ/4z4kwbacESbtRgSYg7pwErBljAtX3ErjtSx10cbt0aKgyHY8cUME1FabTp1Wq89aPtHqtQt2xWnSX5YXqzvwlumvWNBWSkqG7DR2iukcO1qG90uWuwFAd5pcoYc2DzN0nukt4bTfTY+816bmjxdyz6Zjo4v763me+kF6Zwbr3/KOqT+IFfd/4z1XfkB91RFSlimhtMpFBpSqy/gcTdWau6l+9w0TXlUhM5VoTu3O2DCh5wsStHS3xea/ohMI+MtBTpAelt5PEiEw9OKFRhgQk6aTwtirpdJgeeuO0Grb/ph5+7Fs1YnuouX/PB+qB8utm5Btr1IMFx82osq0yOq3ajJn3kowdYMy4sQtl3OU67Yl5UXnqdumU4AUqZecGPb5pkprw5k4z8dB8SV2xzkz6ZKKkzVxqJq+PlSkjsszUYiXp4cNNxrRmybjZw2Qm/iSZJ4fp6T0vqelfh+us1jo1Y0urfrh+l5pZ1qAfqd6gsuft07Mql6vZqfVmzqp1Mjemxjyat1TmBW82OZ4syWkqM3kRwyXvQK7JD+gh+duSzfxTXnlsfY5ecDBcLSz26MerWlVBZqReVN6gFg/uoJcU7FOFIU26KG2LKvIGmuKkGimuP2uWhW6WZdUHzPKWMnmysso8dThXVpRUmKd3J0tJdqFZuTFK2vr6+fq18ffz/c+9vN6Kvj4+Xu9b4uvv9ZaX+rR37zu6u7r1ycTUDJ/JY+2Vbq+H7DU5w/3NfX1v3TP+RRG89mT7h9UgZUDqgBQCqQRSCqQWTlsMpBpIOZB6IAVBKoKUBKkJUhSkKkhZkLoghUEqg5QGqQ1SHKQ6TlsepD5OWyCkQkiJkBohRUKqhJQJqRNSKKRSSKmQWiHFQqqFlAupF1Iwp60YUjKkZkjR0FWNQ9k4tm7uSdrCIZVDSofUDimee7C2ekj5nLZ+SAGdtoJICZEaIkVEqoiUEakjUkikkkgpkVoixUSqiZQTqSdSUKSiSEmdtqZIUZGqImVF6ooUFqksUlqktkhxkeoi5UXqixTYaSuMlNhpa4wUGakyUmakzkihkUojpUZqjRQbqTZSbqTeSMGRiiMld9qaI0VHqo6UHak7Unik8kjpkdojxUeqj5QfqT+yAE67AsgSOO0aIIvgtKuALAOyDshCICuBLAWyFshiIKuBLAeyHsiCOO2KIEvitGuCLIrTrgqyLMi6IAuDrAyyNMjaIIuDrA6yPMj6IAuErBCyRE67RsgiOe0qIcvktOuELBSyUshSIWuFLBayWshyIeuFLBiyYsiSOb23/q8smtOuGrJsTrtuyMIhK4csHbJ2yOIhq4f/L1+Q/SLJ/iA6dWBsQmxcdGp8fGx8bFzQ3zgwaOAkCwAA", "America/New_York": "H4sIAPygLGgC/+3Wf3TNdRzH8TtmGGukibBENcM2P1p+rVqhNdzmxxaW5qM2O0PtHTVTmgppzqnV4UzFmciPEebXZNT8bBydfjBEP+ZDLMn4sEJW9/Z5fqq/+sufndO9534fO5s/3dfznZyaNb6H51+voL8/vM7//fMtL9tH0YpwWbztZ/X+ax5Z8t7namnGKflg5k962YR1sjx2pVox4oBZGZavinuuMcW+5Xp1izfN6qo5+sNaMWvKs/TayuFmXdFgXbLpHrM+L0pvWDRMNmYOUpum95TNCV1V6Zgw2RJxk/qo31XZGmRUWZvjUlZ9SG0P/NVsr9isPj79tfmk5CtdvrfM7CjYqHcuW2h2Zc/Xu2e9ZPYk5ei96WPNpzGjdIV3uuwL7av3R6XJ/msj1YGQeDlwrI/67HUjhzr+IodUna58/rQ5HP+9PpJSYY6236G/ji02xzxL9PGwuea4nqm/8a2Ub3dm6O+q8uX7Va+qqvKJciI/Xekir5zMelidyouRHxI7qdNpzeXMyGhdnRBlfuzVTJ+NCDU/tbyszwVdMueuHNY/V1ea80e36JqKUnNhR6W6WHJIzOJSdalgs1yesUDVZhfKL2OnqV+TcuXKA4+rqzGpcq3TVP1baJxcbzRaX782ytSd7ad/P9bX/LG/nfZtbWv8K/3as8BnAuac1PWmalNffCpQ/SENhmoVFH9CGnbbrRq+0VoaN1umGq+db4LNa6qJni1Njy/VITsz5aayWTp01UzT7N3xunl+hrl52iO6RVaCuWV0Zx2WGGla9mmqb41sYlp1iFStG9WY2+o1UbddDpY2J2tU24Pnpd2uL1X4hi/k9iUbVPscj7njlXmqQ8op03FCib4zdq+5a9Db+u6wFSai8xQd4dsjkcEpOrJquXQ+10t3KZ8jXSuTVVRRlkRvulfF5A2WbvNaqe6ZmabH5OuqZ0KiuWf4dyo2oou5t0e56tUwxPRu843uXX3R9Kn7WPetOGj6fVuk40ouyH3bX9b3F3wlDyx8Usdnb5QHZ81QDyXNl/7p49SAmBwZOKC/GlhbbBKixuqEyrkmMeRBnbhpkhlU01EPXpQvQ47GK+/0ifLolg4qaYxXhhYGqmFxMTL8+Wo1om1zSU7Zr5LrauWx2NXqsTOhZlR4hR6195IZ7SvWqcsqzeNVc/WYWaXmifJJOi19gRlb9KhW3s0ybs5E9WRUoTyV6VXpIbmSkRCjMmpSJTOiucr8PE6ygmpV1tpwmVB9RE0s7GsmfXlJP53T1jxTUqmzU3xGCkr1s7HaTM5eoKeE7TbPJU3Tz/lOSE7vQpVTtUtyW+Wq3PIPZNq1VPVC0Wx58Vicmp6XKS9tDVd5aYky4x2Pqh9Q78begQ3qBfxH337/tiKPx+/ftzMg0O8vW+9p9M/T/qapezYb4k32DBxgPyPsZ6T9DE1m3wLs2z2Tb2AL/faVVt+8hWwisovINiL7iGwkspPIViJ7iWwmspvIdjrtfiIb6rQ7imwpsqfIpiK7imwrsq/IxiI7i2wtsrfI5iK7i2wvsr/IBjvtDiNb7LR7jGwyssvINiP7jGw0stPIViN7jWw2stvIdiP7jWy40+44suVOu+fIpiO77rTbjuw7svHIziNbj+w9svnI7jvt9iP7jzQA6QDSAqQHSBOQLiBtQPqANALpBNIKpBdIM5BuIO1A+uG0DUE6grQE6QnSFKQrSFuQviCNQTqDtAbpDdIcpDtIe5D+IA1y2g4hLUJ6hDQJXZfcf2TbJl62T+4LZhuFdAppFdIrpFnui2a7hbTLafuFNMxpO4a0DOkZ0jSka0jbkL4hjUM6h7QO6R3SPKR7SPuQ/iENRDqItNBpe4g0Eeki0kakj0gjkU4irUR6iTQT6SbSTqSfSEOdtqNIS522p0hTka4ibUX6ijQW6SzSWqS3SHOR7iLtRfqLNBjpMNJip+0x0mSky0ibkT4jjUY6jbQa6TXSbKTbSLuRfiMNd9qOIy132p4jTXfariNtR/qONB7pPNJ6pPdI85HuI+1H+o/cAE57ByC3gNPeA8hN4LR3AXIbIPcBciMgdwJyKyD3AnIzIHcDcjsg9wNyQyB3BHJLOO09gdwUTntXILeF094XyI2B3BnIrYHcG8jNgdwdyO2B3B/IDYLcIcgt4vT99X3lJnHauwS5TZz2PkFuFOROQW4V5F5BbhbkbsH/b5cbv12C7R9i7T/o6u0Z3SO6W1dv9+7R3aO7Bf8J8/qOveANAAA=", "America/Santiago": "H4sIAPygLGgC/+XVbUzVVQDH8f+9l6d4SBFTIS20MAqEA1wFDPBIEpCCt8DHLmTqUNAAiYdSSmMrsbZIZmtNm7NHdU0PWAFL5llF9EB1WTGyydqa2GpNRk+Wprfz/Q9e9ap3bf3v/ufDYLy52+97StdXVqRZ/3hCJl6ewxM/T99jjjaRn3fQO+o53Pxd3xFrh1blTX0dTdmyc6nlO7W2Vr81z+15O/NV+Y5ri68rZlh3nT/o6b7q1T39sZ6B2dVyYPv3vi/PtemvZg6JobRVeqixXV4dzJLX2i8r/8Bn2qo7pxwNHu2Uhcq1KlUHxCaowJyVMsiKUMFhp2Xwt2Mq5FqUvO7MoAod+U2GHb0ownuHZUSrT1z/Uo+csrVTTH1qSEcWHBDTKrp0VHyjmH73i/qGyHY1Y/4uPWO8Xs0KKtOzBler6AtLdExHhrrxC6+cvT9GzTmZI2+q/Uvd3BYrY3e7xNwap5yXeUXcUnxe3ho9IuIyLB335xkx/+c/9G1nj4j4Sx/o29/rVXcMv64TXj6sErta9YKWJ1TSC1U6eeMmJfbslSm5eSp1Q6VMyx4WbrlcLgxbJhZFdMv0oCGVYU2RGZ+GiMwfEvTi4z+KOz+O0FlPD4jso2M6p+qEWNI6qGXJJ2rp1lM6N+1NdVfB83pZ1LMqL6VT5v1Sq/IjD8j8MacoGG+UhadrxD2Da+Xybkut6Fgsiz4MFsWeFr3y0AnlyT2r721+Tt2X8Lss8dap0rCv5Zr0C2LNyZ/0upkfiXVtn+v1l46L+2uU9h7bosrqm3X5vkL1QGm53lCZoB50S72xMEJtmlMmN8ePqc2/BuiKaeGiYmSu3DJ+UWztdcnKQZ+oOjQqt3V0iu3N/fKh/QdEtfeYrNmpVG3WM3LH+nZVF/eGfnhxvaoP3KcbYlarhtFtuvFyhmrqK9KPfBOjHn0tWe98P13sejJSN78SLR6rTpKPt1wRu4unSofT4XIEOCc/Lqcr0JxBwf+Rj9/f+65l2WeA39+jrBC/v19b4ZwOcw75HFMnT36/oqjUKjHvArHQvG7zTo7Q4Zi09F9M02+eyr1z+pCJIjNFporMFZksMltkush8kQkjM0amjMzZ1kwamTUybWTetmbiyMyRqSNztzWTR2aP9vTtfzTz5zEJsL8BkwEkBUgOkCQgWUDSgOTB1iTC/qJMJpBUILlAkoFkA0kHkg8kIUhGkJQgOUGSgmQFSQuSF1uTGCQztiY1SG6Q5CDZQdKD5AdJEJIhJEVIjpAkIVlC0oTkydYkCskUkiokV0iykGwh6ULyhSQMyRiSMiRnSNKQrCFpQ/KGJA7JHJI6JHe2JnlI9pD0IflDEohkEEkhkkMkiUgWkTQieUQSiWTS1qQSyaWtSSaSTSSdSD6RhCIZRVKK5BRJKpJVJK1IXpHEIplFUmtrcosk19ZkF0kvkl8kwUiGkRQjOUaSjGQZSTOSZyTRtibTSKptTa6RZCPZRtKN5BtJOJJxJOVIzpGkI1lH0m7P1uQdSTySeST1tib3SPKR7CPpR/KPXAHINYBcBch1gFwJ+D+9FkKzzF9y3OZMy0ksykxKSVqUnOpOLHJP/BT6Nywxre/TCQAA", "Asia/Tokyo": "H4sIAPygLGgC/wuJykwzYsAALFAMApxQNk8DkLhux1Rw/W3khxs/fhXcPGv94TY7w4fba2U/3Hn26MPdnv8fmBmZIJCBoZkZpLtnASNQc90EBg4I6eMbwuDlAsTBISBpRhAOIcER/4Eg9dCSAhANcgyYBjoIRIMcBaJBDgPRIMeBaaADQTTIkSCabIdyATm6llwADEjmDTUBAAA=", "Australia/Sydney": "H4sIAPygLGgC/9WUXUzVdRyHPydlxEkly/Gq5EsmGAJHxQ6F5guvKYZyQKA04k2xF4GTipX49aVRm+9dyIwZ0hxdVBitaY5FlBsrBFYXvZDm6KZhbcybjJnZ//njZTfd1XO23/PfuTjn4vf/PIHSmuqF+kcm3vHhO89TzDla1n5uLV3J6gt8pL7eKrt0rsj627NtoDWowaYEm1CbZhMnT1dIfqyF/O630ORbFvptjIWFX7Wwj/8072iP3fN2tCZ9/5MmN97UlPOfKXzTFd3b3Kapy7p1X8MB3R93WtOKqzXtr/2K8OcoctIbFjWr0qJ691qMJ8ti2issdjjepjdl2ower8XtarEHTnRqZkmjzbIBm73yLc2p+VUPzt6tubn9mjt6TfMSOjRv8JISwo4poeMDzR8J6uHmryzxmyO2oOE9S+qss+Tiw5ZyvMB8G0ttYX2qLVqabovXR1rqjDhb4huzJbdk/tgI+S//bGntI/Zo10V7bGhI6WeGtfRCl5a99oUeP3lKy6vOaMX+C7Yys0mrKlosI+kdy1zVaFkhq5U9p8yyb7Qp55c3lfvdAT3Ru12rz1VrTfsG5Z3I0dqmND25c77yawttXVmWrc9/xAqWx1sgJdoKZ3qtKPymFd3+zTaMXrHiqwNWMthtpd1n7anzl/X0u/3a2PypNr3eoWcaWlW25ZieLd6n8pygKvyVqowvVFVUlqqn1tlmT7ltvl5gW4YzrObrVNva85A992GkPX/6bnvh6Ji9aNdsW+2PVrs1VHUlf6g+d0TBtCG9lNCn7dFd2hH2vnaMndLOkSNq+MG068s6vfxJuV7pPGSvtjXa7uPbrHFfme2pX2cTPHf9hz7SoYu81ifPepy3+mCrwsbPNXkBrcjM4CgISB6PAv9iG7cdghF70jEbce3sBLMV185eMJvB7AazHcx++FE25P6JsyNgS66dPWE25drZFWZbrp19YTaG2RmwNWBvwOaA3QHbA/YHbBDYIbBF184egU0Cu8Rs07WzT8xGXTs7xWwVs1fMZjG7xWwX2C9mw5gdA1sG9gxs2rWza2Dbrp19Axt37ewc2Dqwd8zmMbvHbB+zf0wDMB3AtADTA0wTMF3AtMG10wdMI1w7ncC0AtMLTDOAbgDtAPoBNAToCNASTE+ApmC6gmkLpi9AY1zfGL9XWgP0BmgO0B2gPUB/gAYBHQJahOkRpkmYLmHahOkTplGunU5hWoXpFaZZmG5h2gX0C2gY0DGgZUDPgKYBXQPaBvQNaBzQOUzrXF8fv1eah+kepn2Y/mEaiOkgpoWYHmKaCHQRaCPQR6CRQCeBVroeG79Xmgl0E2gn0E+goZiOYlqK6Sn+PzfVy9MCXwrfJub5UpJ8SSmJeYtR8iLv345+21iOCAAA", "Europe/Dublin": "H4sIAPygLGgC/+3WWVDVZRjH8WOIAm6v5paovEYuGOIBl5QkcyUUSfSkpBlaippkSMaIZuRUlo7jPDaUmZqvS0qKuOGK5hrqZC4pLpj7Bu5rooj2fv863XTV1EUXnTPnfP4zeOec3/fx9BmaEOb6y8v3yYfX2SfPVT+2X9MbrJgy/WC5yjP2uM3MeVvNdzNmmllTaxnz2To9O+WBmTNohp47ZoeZF7PGfN+2WM+v318vaJirMxoH64xLRWaha79ZmFdNLyq8rjO3J+rFO3/VWQti9BKTapZ+7tbLvtxrlidFmxXJy0129xCzMqqPXuVWZnVYillT6aZZWyXOrL12wKwrdOmcwzf0+qO99YY1+/WPyx6ajd+s1Jum++vNo6bqLaNL9Na4VL0tdp75qVVfnRu+WW+PO2i25/uaA1EndV7deuZgTKY+FNxIHw6ZrA/f+0rnV0zS+Zcu66Pnapjfft6tj227Z45nXzQnsqrrk+m7zKnkV8zpYSP1mR6NzVmPmHNh5c35iMX6gn+QLqjqMQXF5XRhyQh9Mf+KvnSsp768bo++suK+ufrtMn1t3GBzfdZYfWNAlLmZFq9vdUnQt+Pb6Tv1Kpjf2wbqu65rpijAWxed3GfuPbyg729aYYoLvMyDMYtMyfacJK+kXF06KE57d8/QZXzDdVn3RF22sLb2VYnad8dD7Xc9RpdbXsuU3+vWFaY8MBWXVtGVRhw3alqIqRy7yVRJVebp0DmmatxNUy3wklRvlSs1vH6RmjUzpOaZJfJM0USptXWK+J9aoGpnZqk6myeoupNEBcwepnRisqo3rpt6NtqjAgc0Vc8Ft1T1u3SVBuVrqoaNm0jDO80lyK+SBOVVl8aFN+T57CIJ3rlfmqTnS8gPK6XpyPXinjBVQvsdUWHJ2apZRI5q3uNr1aLOTNUybJRqWZKmWvmnS6tjA1Tr4hQJ39BBvXg0TtrMj5eInHB5aXw7aTu9trycECjtPm2t2nf2lg4D/VXH+hekU4cS1dl7p0QGnlCRV8+rKK/NKmr3DtXlzFzVNWuhit61UbpNnqRiMmfLq8OHq+6TPpHY3hOlR+Ig6flConiiI+W1GjHSKzhIet11S1y1ziruUBV5/U4j1WfVbemb56feMJVVv+zL6s20Wyo+fbfqH5+nBoy9KG+1Xa3e7rdLBgZMU4MisiTBZ6UMriMyuGCqDClJlqE7UuWdYx4ZltFXEnNHqHe/iJDh83uq94YESNL4FmpEbBuVnFBDvR9aV43sdE99UNmlUppWk5Trp9Woindl1N5tKvXqERm9dL4asztHPpy2RcZmzZSPUudJ2uQ0KfVUaa8/397/9tunTNn/wPvRo/uVXC7nu7TL5RNQysflqqhKlXeWSTnPPjyWcp5dPo+/o7t5XB3tJ6qnx9XefiLts/03zuvJqtkHz9/Yvkf21Xuf3w1kAx3tDiJbiOwhsonILiLbiOwjspHITiJbiewlspnIbiLb6Wj3E9lQR7ujyJYie4psKrKryLYi+4psLLKzyNYie4tsLrK7yPYi+4tssKPdYWSLkT1GNhnZZWSbkX1GNhrZaWSrkb1GNhvZbWS7kf12tBuO7Diy5cieI5uO7Lqj3XZk3x3txiM7j2w9svfI5iO7j2w/sv9IA5AOIC1AeoA0AekC0gZH2wekEUgnkFYgvUCagXQDaQfSD6QhSEeQliA9QZqCdAVpC9IXR9sYpDNIa5DeIM1BusOPgPYg/UEahHQIaZGj7ZHzA7JNcrRdQtqE9AlpFNIppFVIr5yftW0W0i2kXUi/kIYhHUNahvQMaZqj7RrSNqRvSOOQziGtQ3qHNA/pHtI+pH9IA5EOIi1Eeog00dF2EWmjo+0j0kikk0grkV4izUS6ibQT6SfSUKSjSEuRniJNdbRdRdrqaPuKNBbpLNJapLdIc5HuIu1F+os0GOkw0mKkx0iTkS4jbXa0fUYa7Wg7jbQa6TXSbKTbSLuRfiMNRzqOtBzpOdJ0pOtI2x1t35HGO9rOI61Heo80H+k+0n6k/8gNgNwByC2A3APITYDcBchtgNwHyI3gWPD4/5VbAbkXkJsBuRuQ2wG5H5AbArkjkFsCuSeQmwK5K5DbArkvkBvD0d4ZyK3haO8N5OZA7g7k9kDuD+QGQe4Q/P8W+ee3iJ/9c5NQ+zd3cLdQd0iLEGszaBrq9weS4h+PpA0AAA==", "Europe/Lisbon": "H4sIAPygLGgC/+3We1TPdxzH8V9LLgkfzLXwpRlZIyEyzUjMKpeEXKOSEL5yGYZ+I2Z0nA/D5jZfuZ6W+31Y7kRymxHih7nO5WtYzMw+z282bDs72zk7+2vf36lHfuEPTq/nO7xzn1hf2x+eIs8+eC48+9rdrj5NuzLFPie4vz7n5332uXMf2+dljNM/H1PLNj91g2lERtkXTL6hpzS5al84YKC+yNPdtrh1ipnqckdPvRppLs9Yaq5Y6mmuNFrrqz5yMVd/3M9co1fR1yZM1Ne1yadv9A3RNxXbr296ulnffCdV37p/o7lt0zLzq/mRevpnk8zts01zx/B4c2dcN3NXRCtzd2MXfU8DH3Nvw5nmvog0fV/2eT3D+ZiecVfTD1yMMg+uDzMP3lzoyLQHOzLPppiHZtQ1D+0K7pGVkOLI2pOuHx5a2jyc1ttxJCzJcWTxAv1o+EPzaHJLxzHfWMex8eP04512m1+3XG+e8D+qfeO1UztZbq12qtAi7dSjGVr29Qna6ez3tTMZcdrZzZ20nDVJxrmUocb5abGGY2xH40LCu8bFKH/jUlgN49um7sZlXzfjSuUnxlV3L+1a4fLatceFtes3ftJunL6lfXfgnHbzy8PardTt2u3Zq7U7k1I0c+Qn2t2+Sdr30SuNe+0M437gVONBnbHGD56DjdySMcZD5/bGw3vNjUeX6htuX9SwFZnjbis62c1WLClIiiF+snhMNVkivKwsGdpMvFrnR1nKM8deumSWvYxzur3MvVX2spcW2Msdn2Yvv2uc3X3rSptHmmGrMHeqrWKyFJVGfSi0+ARRuWu0qBISLjwbBYnXvP1EVY9q4nW3sqKaS6Cs9qCurH65qvQ6UVrW2FNAvrHuofRedF2+Of20rJl0UNYaslX6xCyXtbtlC9+EdaJOwBZRN2ymqFdhnvDzHS78niSKBu7TZYOcnsL/8TDZcFugeOtMhGy0JFIGbGko357QRDae4yHfifWUTZL8RdPmLjIwxl00q3pVBgU+Ec1dMmQLz/Oixe0roqXzDtEya79479JCEbwiVYRkpsvQKcmiVdoC2XrAANEmeZxs23GSDIvvJdvVj5fhIS1k+zKtZAdvL9kh10dGlGouIk6WkJ0eVBedN9yXXU64iq5GcdFt3U3RPfGeiJyeJXpEnhA9R9+QUY03iuhumTKm0izRK2CFjC24XvauIGXva5/KuCcJss/+EbJvTrjst6yLjN87SPSfGCAHLGknBsZVkvqEemJQ20YiIbaMGFy7ohgS9EgMLW4Tw2qVksPMi2J40Vw5/MhuMeJ2thy5aon4IGuLHDVrpxy9Yp4cM2KRTJySKG35nV55/nLO95cvl999/N1XgT/5iwvmf+FVyNV6vfTev/R6+jQ3mtUpKpzyWfNT6OWvPTSnIs/ft5X49bt5X6vvln7x94eEhts6BrXjEx/qV4FBfKh31OP025O3dE5574T/g018qp7uAW4VkG1E9tFSbSSyk8hWInuJbCaym8h2IvuJbCiyo8iWIntqqTYV2VVkW5F9RTYW2Vlka5G9RTYX2V1key3V/iIbjOwwssXIHiObjOwyss3IPiMbjew0stXIXiObbal2G9luS7XfyIYjO26pthzZc8uzef8e7Lql2nZk3y3VxiM7b6m2Htl7S7X5yO5bqu1H9t9yfN7/Fx1AWoD0AGkC0gWkDZaqD0gjkE4grUB6gTQD6QbSDqQfSEOQjiAtQXqCNAXpCtIWpC+WqjFIZ5DWIL1BmoN0B2kP0h+kQUiHkBYhPUKahHQJaRPSJ6RRlqpTSKv44aFX1g+Uapb1o666xUO7kH4hDUM6hrQM6RnSNKRrSNssVd+QxiGdQ1qH9I6H5vHQPR7ah/QPaSDSQaSFSA+RJiJdRNqI9NFSNRLpJNJKpJdIM5FuIu1E+ok0FOko0lKkp0hTka4ibUX6aqkai3TWUrUW6S3SXKS7SHuR/iINRjqMtBjpMdJkpMtIm5E+I41GOm2pWo302lI1G+k20m6k30jDkY4jLUd6jjQd6TrSdqTvSOORzluq1iO9t1TNR7qPtB/pP3IDIHcAcgsg9wByEyB3AXIbIPcBciMgdwJyKyD3gqW6GZC7AbkdkPsBuSGQOwK5JZB7ArkpkLsCuS2Q+wK5MZA7A7k1kHvDUt0cyN1hqW4P5P5AbhDkDkFuEeQeQW4S/P8u+W/uElf1m334U96hdWrWq+lTq7Z3aG0fvnL9BURZ00nHDQAA", "Europe/London": "H4sIAPygLGgC/+3WaVDVVRjH8UuICioeTdHE5RipYYQXSnMjcw8FcrnpTVM0EzXJkIwkM2oqS8dxHhuLTM3jkpILbuBGi6ahpqKmmGHuqeC+JoZg5/vXmmZ6UzNNr+IO93PZhhcMz/fn6TciIdL1l7eKd995u3L3dbU37dOMxkvNjP1+euYut5k1f5P5dOYsMzu9jjHvrtdzUm6ZuUNn6nnjtpr5cWvNZ+1K9IJGg/TCJrk6o2mYzjhbbBa59ppF+TX14qJLesmWRL102/c6c2GcXmZSzfL33HrFB7vNyqQYsyp5pcnqEW6yo/vp1W5l1kSmmLVVr5h11b1m3cV9Zn2RS+ccuKy/ONhXf7l2r/5qRZn5+uNsvWFGsN44Nl1/81qp3uRN1Zt7zjfftuyvc1tv1Fu8+82WAn/zXVBj+S79Gdm+p77seLWN7FzhkrxBXrVLjsvuUQNlT3KQ2lMSqb4fUab3Dgk1+6KP6vz6DU1+h1LJP3JU7Y9boveX+ZoD4VP0gZsf6oLAJF1w9pw+eLKW+Wl7nj60+aY5nHXGHMkM0ken7TDHkp80x0eO0Sd6NTU/e8ScjKxsTkUt1aeDQ3VhDY8pLKmki0pH6zMF5/XZQ731ufW79PlVv5oLn6zQF98aZi7NHq8vD442V9Li9dVuCfpafHt9vWEV80u7EH3DddEUN/DTxUf3mJtlp/WvG1aZkkJfc2vcYlO6JSfJNylXlwv1ar8eGbq8f2tdwT1JVyiqq/1VovbfWqYDLsXpSivrmMq73brK1FsmcHl1XXX0YaOmh5tqPTeY6qnK3Bsx19TwXjE1Q85KUMtcqeW7U2rXzpDaJ5bJfcWTpM6mqRJ8bKGquyRT1ds4UdWfLKrBnJFKJyarhm/FqvtjPCpkcDP1QFgL1ahbd2lcubZq0vRhaXL9UQkNqCqh+UHStOiyPJRVLGHb9srD0wok/PNsaTbmC3FPTJeIAT+qyOQs9UhUjnq010eqeb1ZqkXkWNWiNE21DJ4mLQ8NVq1KUqT1lx1Vm4NeabsgXqJyWsvjE9pLuxl15YmEEGn/TivVoYufdHw+WHVqdFo6dyxVXfy2SdeQI6rrhVMq2nejis7bqrqdmKe6Zy5SMTu+ltgpk1Xckjny1KhRqsfkt6Vn30nSK3Go9H4sUTwxXeXpWnHSJyxU+txwi7dmF+X9obo8c/1B1W/1NemfH6CeNdXUgKxzamDaVRU/LU8Nis9Xg8efkefarVFDBuyQ5xtMV0OjMiWhYrYMqycyrDBdhpcmy4itqfLCIY+MzOgvibmj1YvvR8moBb3VS8MbSNKE5mp0z7YqOaGWejmivhrT+aZ6pZpLpTSrKSmXjquxgTdk7O7NKvXCj/La8gVqXF6OvD79GxmfOUveSJ0vaVPSpJzPPf/w4fvH485Hf/8n/Sr89ZPlK/zXj9u3b2dzygKVT7nf71td7VP599eBylXuz1+NifW4OvT2uLpiJ/vC5ePjw9Odi+jj4/kHZ9P+8tt1BvhvR86noz2hyBlFTilyTpGTipxV5LQi5xU5sciZRU4tcm6Rk4ucXUd7epHz62hPMHKGkVOMnGPkJCNnGTnNyHlGTjRyppFTjZxr5GQjZxs53cj5drQnHDnjyClHzjly0pGzjpx25LwjJx4588ipR849cvKRs4+cfkd7/pEEONoMIClAcoAkAckCkgYkD0giHG0mkFQguUCSgWTD0abD0eYDSYijzQiSEkebEyQpjjYrSFqQvCCJQTKDpAbJDZIcJDtIepD8IAlCMoSkCMmRo00SkiUkTUiekEQhmUJSheQKSRaSLSRdSL6QhCEZQ1KG5AxJmqPNGpI2JG9I4pDMIanjn47cIclDsoekD8mfo00gkkFHm0Ikh0gSkSwiaXQOiM0jkkgkk0gqkVwiyUSyiaQTySeSUCSjjjalSE6RpCJZRdKK5BVJLJJZJLVIbpHkItlF0ovkF0kwkmFHm2Ikx442yUiWkTQjeUYSjWQaSTWSayTZSLaRdCP5RhKOZNzRphzJuaNNOpJ1JO1I3pHEI5lHUo/kHkk+kn0k/Uj+kQmAzABkCiBzwNFOAmQWONppgMwDZCIgMwGZCshcQCYDMhuQ6YDMB2RCIDMCmRLInHC0kwKZFY52WiDzApkYyMxApgYyN5DJgcwOZHog8wOZIMgMQaYIMkeQSYLMEsfCO39X5gkyUZCZgkwVZK4gkwWZLch0QeYLMmGQGYNMGWTOIJMGmTWOdtog88bRThxk5iBTB5k7yORBZg8yffD/+fOvzJ8A+xW3/Y6w2EfCm4e7m0WExUa4eRXwGyD3D7RQDgAA", "Pacific/Kiritimati": "H4sIAPygLGgC/wuJykwzYsALmIGYBYiFGkBE6CcGfVbtBYxMzP//5wBF/v/PAkr//1+cwMDFwHDkAQOfj28Ig66hgYkBiGTQNjRhCCHBkv9AUGfuAbILbBkIkGwhlw2QtNM1NOECAJ3gDHjgAAAA" }python_dateutil-4.0.0/tests/resources/data/zoneinfo_slim.json0000644000000000000000000002117513615410400021510 0ustar00{ "Africa/Abidjan": "H4sIAPygLGgC/wuJykwzYiAIGKEYBEIIawEpZQJijv9AMOnZJA/G////WEAlWXx8QxjcgZgLSBhwAQDxCHuHggAAAA==", "Africa/Casablanca": "H4sIAPygLGgC/82Ve1CMawDGdykTLZZJTGcci3KLScYtnGJqCBXZjZWEhi7sTtljKs6arMtqKrFjVmgnS1ZTUQ3RDblUymXRTlPLMsblZMbJpWGW4Ux2n8dfmPGv75t3nu/3vO+3+9vZd/eTRSfFTxH88hB+G85D9utbGh3D1TFEPY7jUOQngzObejx2OPOG/HQK0toFbj0+5a0zH047KUC+Hgv+7KOai7z2JsX5om6bdu9ANinfOtP9pQhvJlq3ANy/JQjzA3K7sX6gJRIsHlsI9qo6hfV/DkvG+tB5/2I+tG4U5heN9sL8on1t4MW2K5gPW/0CHJ5XDY6YmoP7lxiMRmcudatj+h+VIBOKwJHqncyOW8hlrgVMxd9I6YxtzLKRTNt83C8LiwJHDY1hqp+gjyp1AS+fOINpD0SukO5lak5jnXyIjNkuQb9S8p4plzI/TMd8dFUvcLTdAF7lcwW8qm0YOMYcDI75kgiOza8Ax1oGIteq5OjXGtXguKBGcFyaN3K9pwL9+hAdeEOXBzL+j5noE2o14IR3/HxJunHok+rDwZsS7jH19FdO+wusVNA32f05+uRZfcEp1kjwZjE9VeWf0KseDwdv0fL72lJJz1RZf3BqNj3TJ5xHny63grd+HAXe5kfPf8wt6NV96LndtBn9dosenKF6DM4ooadm4R70mrQS8C7JJGYEPXd3cb/s8aantmEeem13PDhTVwbObKFnVuJy9FnH6JkT+D/6HCU9c0UbwbnB9Nz/bDD6A4Omg3U1NcxOeh7cOwZ88DI99avN6PXZ3eA839ngvDh6HhE+RX8kgJ5HO7LQ5/ehp8FkBxse0bNAzf1eUHIdbJRyfxs19DwhOQc+IadnoT0a/UmfDLCp4QbY9IWeRfnJ6Ita6Vms8kRfbKRnadAucGkqPc94+qI/E7IEXPZfK7Lci54VtUHginf0PHugE/3ZendwZSx/R5V6el6Y+hn9BQU9q90L0VcH0LPGKgbXiulZV16Fvu6RDXxJu4ZZSc966W1wfTY9r07g/8JV+WHwNfsT8HU/ejaYM9E3utKzyeSHvslCz2aVAdxcTM+bC0PQ30xLBN8e8YoZQc87XXKw2ZuedxsE6O92e4Pv65Tg+830tCR6oLccCgC3BV5kKujZLhoPbg+mZ8fTe+it4g/gBzXpzE562rQvwLbLIZJewu/O3j80Pzl7u/xWZ0/Px+d4AImFLniSuDmvBbgWuoWFywS+k/0dY7Kg3xzHVeAk/35fATFCsDt/BwAA", "America/Los_Angeles": "H4sIAPygLGgC/73Ra0xSYRzHcVQUwRuZqJEVqYkgcvOG3czbvBRTk+yyZtnKRltT01y9yGjZxTUDtBddFmGtlitD6k3NMlybq7VuuDVvmVmpMy+ElniJ0zk/e++7ztnDlw/nPP/nBapd6mI5bdHL5d+iLtXiW06Qy51cAQR5FdK5FqqGO5lGqjdaODqqxrNCuOHqNPy6hgtbw6ZK0aIINtWPzordVDs1TXiv2/kC7bHo8Ly37zb8qfE+2td6Dv1ccxHtN6jRL+pSdKBqM/o1ayv6rTAa/S6IRQczsjF3yD8PHeaLFmqPQUcYvgu1ctAfgzZ01DyNjrVb0XF9FzphGsdcW1kL/FP7HrafbEMnSx6iU3tuob9yLqG/k86g05JK1BF5E/tn/HbAs57V8KzjNI/q3HAxPN95AP7zMhN2Ps6AibtCNv6dywIe/tPz3rDrMS/YrSxSR5VexDdSdc9jwR7JTJghHYUZtakwk/0WZjY9x36WrRn26jfhuXfXG8z3sehh3ycm2K/xAd5nX9HDS2p0sP/xcnip+ggcsHMbzMlSwYGJCXCQIB4ODs3HecuYwTDXNQ7m2mNx3vKBIDjEGgivaJuBV5od8KqGHphXGYX9q089g0MLfOCwQ904LzxuAl6T/RSO4HyA+UIDzHeOYZ6ApYEFfe9g4cg+OKrVDIs6qjA/2lAPix/thSVVR2FpfQosO1iH+fLycDgmowKOzfeA4/gFcLx8GE5gKGBFiDvOUwxx4cS5IXht+zy8rucVvL45GOdtaLkHb9TOwknXauFNJb1wcnUj5qfktMKp+y/AaRIjnJ52GE6f7OC5upC3Gx357zdB6CNoNIK4rnOhE4RWQ/PEd298srcoVbTcNHLlk2s7uXJVNBYJBfmjSBkjloulIqVMJpaJpay/9iIS/g4FAAA=", "America/New_York": "H4sIAPygLGgC/63Ua0xTdxzG8XIRsIDgtE7F29StFqHlYkXAC5s6RNbgtAQvC+ACkroXEJfhTBxeQBETxUUys7nUodxFKzcnogUVK2FRkToFFSiMoaJoBS8MZuvpd3tvTDwn//766Tn/50lfnKNeq9kQIHrrYff/sh3qt2/RCWuEsMZahSPWwXzANrUFU1Js88jZR/G2+dtuEc795So+mtiFj6U/NNlm3saTOF9ZyPWCVY1m2yyUZOGiwFJcZMnn/pIx+3FJeyY+PpCCS/UafMK4Ep/URmJdxRx8Ks0Xl/36JX3lScvJr9gaiCvDfXDVVxJ8WjoK/x76Cp9xMuNqr1Zc3dOMaxxfkF9jqMTnum/j87om+vT11bg2uxzX5R3GF5Jz8MWMH/ClqFRcnxCHLytWY4NqK31XPEJwg28sbhiMoa/RPQw3tgTjP/aYcfOM5//N+GH2Gb/rJvdmWBv+M9qAb02rxbeVRbhFlItbJXtxqykd37EUkne3LhHfa8/CbcU76W3Xf4M7shKwSavCnZrPcVeaAv8VMQt3x47Gf8fIyesJ96XvfpAnfiD1wA/H9eNep2e49+VN/KjHiB/fOo37DFX4Sa2R/Ke6ZvLNR6rws+xK3L/tEB5I/gk/j9uCX0R9j18uWodfKdbiwVmbyf/HYz4eclmDhwZX0zf8IBT/2xKCXzdMxpYzk7C10GriaTlkMfOMZXZi+80m7JBiibdNx/jXKbY5YoUJO4V1YGe/i9h53wQ80jMPjzyRw36xeTd2Ne3iulvrUfLd65LwqOoM7FGczv2eP2/Ao7MS8QdbluExmnA8do03lkTI8LhgN/yhzBWPny6jb4JLH55o74on9ovp8+rsw5NuPMaTL1zHU8qu4am5ZXhaqoj9H+04iKdHd+EZG3X0zVTW44+X/4g/kRRgqfe3WGq5RJ5MHI1l7fnYuzcIz9ZnYh+jmnxfrQbLK+ZiRVok9js4HvsnJZEfsGkIB4ZH4Dkr72GldDaeG6DHQc7ueJ7XHfrm9TzFwcPncIjhBg69q8XzdU/oW1CzHS/MbsKLDn+Nw5LL8acZ28j/LCoHL05Yj5coUvHSJYvx0oEis73dO54Oju+85T2eVutZrUgkvMrq7ByFF+gpkQvf3fj0/EKlFv6csFYJK0ZYK9QisQCl8KOPKlAeIPfzUfn7y/3lfuI3M5pHyNAGAAA=", "America/Santiago": "H4sIAPygLGgC/73UbUhTURgH8LNNnTmXmuZbWsvSrE2d7qqb6ZzmmqbTlTNfmmYa6iTSxPRDQuWHtD60EiPCQowIk9Cp1ZQUJSp7sXLUWIIShBlFNCzK3nTd+9c++617Oee5vz3PeQ67HK62QF8mISterOXBXNqVlzTSw4keXnb60jcFPmCiQaxSMrFN907DxPaGt/i9gxwZZaKxqB7urU9QMLEviUwwsT+vGvlbQRTW3ZZdQ/4Opxx5k78VedNMG/IDCzp4cEwAjwccRv34ofeofzllQP6Vj0XMRIskB7bUtaBuwRyPuNjyy2jHwmej+Fc1U0a8i6MamK1Igzk5UbCDQAg7yrMUBC+AD3N5QzD3jQ12XvSEV42YYZfpbzCv87OYia7DVpjfPAGvvjIIu1X0we6nLNjPI7UVXlNmgj1D62CvnZfgtR4t6O8dcgz2nquFfZ0KYV/zXthvNhH275XC617osF/AeX84sEcOr6/+A28wCGDBcQ7221jFhoNkv+FNmTPwZr9pOFhK0D/45wgc8uUHvGWyAw6dvw9vvTeM/tus12Hh1XZYZGqGwxpPwuEXK+GIklJYfKIJ+0UmK+GoYj0sSbCiP6VIh6N5KXAMfwCOdbKgXkrcYOlTZ+RlH4ToH9f1Ed7+mA/HnxmHEzptsLyyG05sNsOK7Cfol1TRDydLbsI7Ui/AKZ5nYWVkH/ZTfq2GVR6tsMrGRr/UuTo4bagK3mXOg9MHCOozeuNg9UMu8pmaRvTPutyNvCZ5Et7dcA7eI/yO+mxdDazlvYZzY2exPrfnE+rzfR7B+YbncMF8F7yvygjrbpRjfWFtA1x0eun879cWwcX6pfN/gFLAJWlL5780sBD7HQy1GVlsFoflwP53c9gcR3p2/I+33T58lxDMDvQ3wkic7faxUeLKzCx6tkyw3DPUWpJNjzBxND0oekiISzz9JKfoWSIXqWXhkeExEVGUSE0tP7n8BV0iX1dKBQAA", "Asia/Tokyo": "H4sIAPygLGgC/wuJykwzYiAIGKEYBEIIa+EEYmYg5vkPBKmHlhSA6Ot2TBD6beQHEH3jxy8w/+ZZazD/NjsDhF4rC6bvPHsEpu/2/P/AxAiFDAzNIIMZehYwsjAw1E1g4PDxDWHwcgHi4BAGLiCha8kFAAL0rmfVAAAA", "Australia/Sydney": "H4sIAPygLGgC/63QW0jTURzA8bN0xJaXzJjldOUscjW3/b0xa7O8zBW1iPYnTCgCU/Ct2os9ZAuLIXShXhIbZYbsJVImosjALEEoL9BDhHTB3qwH34ooq53v6d2XzuF3PvzOj/P7wdFbOzsqxLrL8C/k0td/Ek5HRjpy/qRXxHLVJ40ffxHFlFtIX+ujytl27ufGT+F8IogLAxHqizFHVDbNuFCLmdlFDDGesJIbv3lxo3tN+bYQTbmflGO/0Lw6jZsebed91ruPmN39E3MmnmPu2Q+4uW8Q8+qmcEvXdcy3PcatLR3K3z1o8R7Ggqxe5mwrOa+cvYaFhmZlog2ty2VYFAtg8bQZbZfjuON+kn47T3eTl0QX0N7wgPvSzq+4y34Fdx+ZV65+wT2OYeXiHDpMd5XDz3DvSgT39b2ir/PNHSzveoqu5EV0t9xGz70wamdaseJSNVb6fVh1sgCri21Yo/1Qrgn0Wi3M877/TF6bWMH9qRk8sLRE3Te0jP7JFNbdeIkH+x/iofYhrO+Z5F1DIEbe2Kb+rcn1BAON6t+ajUepB0vPkQe/D4oNhv++hbg1I9v3jxgyhbg5IEzHQrqoDzTJI6wLszzLNY+8cYY0j0tzeZyhKom70vwXWLmacIgDAAA=", "Europe/Dublin": "H4sIAPygLGgC/63Ua0yNYQDA8TcVdbod6aaiElJOp3NymbWZMRulmjibM2bxAbP6UK01aWY+mGlmZVkouoiiC91IuZQozV1Kciu5dEq6uJ104X3/r/nabN53z/k9/+d93vPpnEe3cef2QGHCy+TPkC7dxK+kisNCHA6/xGvDY8WgZMbc8lRstZoqmflQky15Mq8eT2WexKx0V8zeX+0pmZMwSuduy6RPJ92h88Kr8MyyEdbPztmC+T4NWOCnku01su+80Czb4sh6oWEAixqjsbjpCZbkh+OF7ET2XzygoUuPPKLLYkKxPK4MK9aqsTJ4I/suaZT05cAErLIbwiv2etn+p1htENhf0zaIV19swGtVzXi9dJx9N45V0rUZbli3Kx1v7h7Den0i3orIY//tJZvohqA6bNS3st7YbolPgztYb5npRbeGF9HPVPOwTX1YdvgottvGyPZ+whfvnXnv5d0H9Ktbw/Trih58U+LEekfaPbozbjW+jYpnvWudH/1Ol4LvA63xw9Jinn9088VuBx3r3SNWtGEsFnva+7D31Xr8VP0Q+8p/sv/ziVK6f98OeiBrDz24NZge2htJfwnZjl8jl+M3Lxuef1/mTf8Q+mmjhzlt7HhMD49/pH/WltMj3aY4mlSIY401MdKfwDSmwVPSzFeP5msLcLJlEE7RJMsa3NFSGS17ZxwVA+FoVeaaLWn9SEPbpI7SthftabvY17TyuBqnRtSifaISp2lz0UE/hI7evSmSTksa0Nn0Prq4FMh2XcDpxmR0rU9Ft858paR7UQnOqDuIMw+loEdOFHpGx6HXvjCcFapD760BOFu1GOeErOF751q70D5+/rTPt4Xoq7CTbXFCP8Mgzq8woqqpGf3T2lF9rhID4q+i5mA6ajc/V5pMMjP9e5v/73vK5H++xZ+PnSDwaSaelR4m4nFpqzSx5vhUMrfg4GUuWISG6YSV4gherxNWiGOVOFeI4a8VZxpVmFajXqQWXSARoFX8BqHWakzYBQAA", "Europe/Lisbon": "H4sIAPygLGgC/43TezBUURwH8N3W1mBlo4Sllk2ijfVIaWqakibDpmEbNEmDkUplNqamaRqxvTAGpWlQ1mI0G3mHRpFHLEVIRV4RIkJSpNKe7+2v/uGcOfdzf7/fuefeOWeu6NDxAGvago3+b5AmWviRGOVYqhyceWU7soNlSIwfjAkjJjmfCoZ/ahEnJ8/Bu4oI5O9dsqQRU+SPJohSH1/UU6NGUJftGkKcdvoM4nQeB/MzXGWYL2eOIy8f8kGcrciEDzN5MEfqinruNSbivBsnYX6wMfIF4uuw8IAKLLZ2gSWadZTzpbB0XA7L6orx/JOS+/Bpig/y5XciEVckTsBn54NgZaA3rPLcD6t3MjG/ZqsA8fNtt2GtZxbyte09UMFooZzkwvo+X8xrKHKjHE3rJb4Ic6bspPbjZYItZZXzUWKjWIZ6Y0051mkK1UG9KesY8q/cJJQZqag3i2ZQb452Qr7FOoDyCnVerV7VqL92KoJt9s1c4huzSvhWrwC+U02nnE2A7cNXYUf7OfheEQg7S71gV75ESuyWhcKe+ADYG+4BP4j3wT5fe9jvZg4/7ubAAWsWHDT6DYc4Zlj3k7o+5Zw6HB75BUc6xuDn+m44+rgJjskr4JfEPDgeKYMTF27CyRMS+NUvB++ZcpfCbw5xcNomHH7nnYU/tP3hDOMg5dReONu/RUp+HtYDc/xEGkkcuDyKBTUljrFEdogdXOFvCrVEulBbuIdNXGnzE/EqXlcYUUe7Ea5mlFNO5ULd/lSo1xoP9asiIKcsB+8zyMLn0AyT4+Ca6Fisv/biZcgNEkOjw37Q2EUEedsd4Tq+HTQxMIXrWbrQlOmA7zOdtoUbBkygWZsONK9ZBjcWzkB++jDcdKsDWkgaoGVIGRT4Z0Mr73Y2bQl98Z3x31hsV1lwAhOdrjxrP5wgm66CLVRV7iqXrkEyNC3c67gIRTQPR3dyIUMZOTiSocyoKVMCUuMLbSw2WwgsrfhCKwG5U/sLOW4AaLcFAAA=", "Europe/London": "H4sIAPygLGgC/5XUbUxNcRzA8ZMKN9GVuqVIiVq53U55mDEzZiOqSXdzMU8zrNUszRAz88KMmV3G8hCFKFT0RPJUoovoQW5reag81e1BD55uqss932Pe4pydfc73f37n3O3e3aNdHrMhVPjrZvP7kDbt329JsR721mPkT+vmsVJRLnnKLysVa+29JZMrRfp0WimeST6NKUkemLq3iLmzW/vpc+uT6fM7H9FpkYV4YXYf6xcnrsF0/zLMCFTLtpmZuyzUyBpdWb9i6sJMQxxmPX6O2emReDU1kflr+0Q650gVnRsfjnkJuZi/WIMFYcuZuy4q6RuhW7HQqQdvOutkO19gkUlg/lZdN95+uRTvFNbg3RwLc/eOF9DFpzyxZHsS3t8xgKW6RHwQlcb8w+kr6LIZJWjQ1bJuqFfgE5WfHpOWYXm1Fz7dNhOf5QhYsUanlKzUv6WrNq3C6gQV69V9ofg8xsLn1KwL4Pkvwhppo5cPbZw7wH3GhkbmayMzuV5rseV6neYQXdd7DOtHxMu2tePLD27MvSqvoF8/6KXf5LdiQ7aK9cajT+mmhAX4NnYL6++WBNLvtXr8EOqIH2dlcb3ZMwBbXLSst/QNo00Dm7G1vgPbXkdje1ElduT9YP7TyRy6c89GuitlF929Nozu2b2a/rxwA35ZPQe/+gzn+rfZvvR3oZM2j5P/H+bGarrX0kz/KM6j+1rk761/5xUcMNyKl/50tvFl3pJ2ATq0X5yBgxUzcIh4QNY0BhXKONlHFnToisRhuR6pko5VIj38cD894poz7bT5Da08ocGRUcXonKjEUSHn0EXXg66+bXpJ1fQydLN9hu7uGbLvruJo8wH0KD2Mnk3pSskxmdk4tmQ/eh3U47izsegdl4A+eyJwfLgWfdcG4wT1NJy4cBHP9XN0p/0Dg2j/r1MwwMFJ1qjCQFM3Tso3o/pxDQYdrUfNpQIM3nIbxf1Jss0ThEE2/7vb/tnl+vc77f77wwZJbyt+UqWNHS/sodav2dvGUVoR7MIjtMLcaK0wX3Ke9cTBeiZaV9QRkzVTNWJwiDoiRJTOHH4BV/8B/j8GAAA=", "Pacific/Kiritimati": "H4sIAPygLGgC/wuJykwzYiAIGKEYBEIIa2EGYhYgFvoPBHXmHg0gQaHQT2BJfVbtBYxMzP//5wCF///PAir9/784gYGLgeHIAwY+H98QBl1DAxMDEMmgbWjCwGUDJO10DU24AMg9a3WuAAAA" }python_dateutil-4.0.0/tests/resources/data/zoneinfo_v1.json0000644000000000000000000002274513615410400021076 0ustar00{ "Africa/Abidjan": "H4sIAPygLGgC/wuJykxjwA8YgZgJiDkmPZvkwfj//x8LqASLj28IgzsQAwDCWBhZRQAAAA==", "Africa/Casablanca": "H4sIAPygLGgC/wuJykxjwA/igZgViHmmBf6cc+y/SMPxiDUFx2++bbi00OjDbdMlDLffqX/4rVrk8PvQ+wKO7JYGjmO5H7hf8DDwJLp/4D1p38DX96mA/3Jgg4D64gKp7csY5CTyP3g4Pmvw2K1U4KUsxeDVe7XA+86BBp/YpwW+03c0+Jn0fPCfs2BBAMfuBQGGsxQC0pcvCKxpWhB44/SCINZ5C4JyihcEm1ctCF6nuCD4jptCiE/oglDxmAWhNQ8UQlezLAjTMV8Q9t1uQXhw+4LwxjUKEaIhChHXFRZEKnxZEBkRvCDyq5lC1HamBVHf5yhEqx5YEH1VQiHmnPOCmD8ZCnGzNyyIu8y/IKEoQiFhQc2CJPujCknlKgopYjkLUlwmKqS+FVFIk7ZYkL6rUSH94wOFzIkaCzL3+ypkp19QyJ76ZUGuqa1Cbs4chXzuJwvyrTgVCm4GLigU2LCgaP1PhaJ7sgtK2hYsKNlyVKEshHdBWXfOggqtrQoVETcXVP5QUqjSb1SoPndyQQ2bxoLapYUKtZenLqgvuqdQv8pWgYkRDTJjiGCBzCxEwv//fzwBxTWfACMLONI5QGwGMJuRw8c3hEHbwBCIDRgA54z2mTECAAA=", "America/Los_Angeles": "H4sIAPygLGgC/9WT/1PMCRjHd1e1ti88nKXL5h5frrVLclQidx0yWymV1ioS0ZfZcJWy6rAy9o7cuJ7lfDnc3qPDaFy3uoZBrDAMY7pjuzGR24s71cSSfCnp9nNd/OYv8H7P6zXveX5/tAv1WaJ34/GW/3Pm7R5S0ivLkSj+sUZO/LWaD+7rpOulfmwf/TzPnh4At1yFqQ0llXTHdYkaawnuOg7TnxU/k8O2hf4q/ZaaLHq6p8+j+8Y59Hf0PPonLZAeqIKpWRMDLYMToVU5Hlo7JkObdAC02eXwsLkdHlV1gvOKHR6bb8MT62Nqz6+Bp2U3qGPjBXqW+ys9X/ITvYj/jl5GfEWdQQbqGlsOrwYmU3d/E3R3bcbXrVnQ05CJ/16NAtcpDQpH1SDaq0LxVm+QFHlhv/yx5JauZPdET/KYIWPpxEck3T6LZfAbySrPo2f7cfJqsrL37TrwqTXzgNNWGFjxC8L3ZhhUSji4uAA+0K/GISnzQR6txaFTp8AwVSj6jkqiD2W+6CcJIb+OYB5+fxgp7EPZ/8IrGlHVxR8dbCQ0jMORm87RKJ0Pjs65A2NCnuDHMWchQH4TlWoLKF1OVnmWgMrxO6vblsE4WxWPrzdSoGUnT6heSkHGNTxx50z6JHsHTioYQ5M1hRic5EEhSh2GTmqlKdIwDFO4Q1iLH0593QLTrvRgeOM1mH7clz+tOQaflXVzxP7t8HnuXZ5hqqCZ8TaelfENRQYxz45cRbOf1aMmcBto6k9gtM9KiK7egzHOuTDnQDXH3sqhuPW7eO7JWIpPXcsJuydQ4vQUnmcASlKEs3Z+B2l7/FkX8gfpHkzD5BFPIfmyAlNc9bDwkAsXOU5AqqkJF9v2QFrGRVxiKYalcQ5O37KLlgXW8vLstZThU86ZmhTKdJo4WxlO2XVZrJf6k74yinOaBVqxOxNX3lDAKoMGv7C6IFenwryyJsgP9cLVuRehQO7EwvhDUCjI2BBWSwbHQy7yLaciWx0Xd5noS4uV1zVk0XqjmTeciiJjWgFv3Ksmd7FELOnnJhG/dxUEc4BIJAg/kNhNEMpKRP37tnef4c0lNk4rSojsJamXBb0kaPveXCx+4/8AaqkZBBIEAAA=", "America/New_York": "H4sIAPygLGgC/9WU6VMUBBjGF0RADoEUQ0EyqBB0XRORs8SENsAV5JBDglcDdxYo3jxWKEQLlGCmmEYGKp01lEsSkTMQWw4JGRpTWUXwgBdCUgR9AQ+C3A0d+9SnPvo88/vNM+8f8AZHyLYL/hvdFzzLyIs9f/+MFEXWePTMPfjxoADzf7gAx2IH8HjaXSqIO4WFTsVQFNTBxeaZUOJ4kkvUhVQ67xsu7c2gnyaQTyplVKYK5FMKPyqvWs2nU4VUcWQTVkp9oSrFEavFy6Em0hxr7ebCz+5PsE6Xod6yB+uHOqFB5xE3tFXD2cFr/Ev5JVK21nNjdiU1FRzm5sQcaknfy+f85dQaE82/isKoTZKC503cqF0Yhe2TodBh7Ikd3a7w21eMnbYPsROmSbV7kK943qKrIW3ctaSRrjmVcLcgn3rMs7iH0ui6uhhvNMXSzd5MvHXiS+hVxmNfZgyQQoL9svdhIFWEf/gshcEoM7wduoKGxEL+09mU7tiZ8N0F4zSsO8bDj6/QvSEVj3TV0mhbDd9vVMGD8k7kozUwll2N4/vyYCIxFx9GJ8Mj/yR8vHYLPBFF4OTSPfSXiQdO6YfT1GQYT99xp7+73fhp+2JS11mxplhDgjw1a2X0k/Ye4lmoBh14irMDCHQ9+1BvZQvofb0Q55gWwJyyHDbgg2BIB9Co5xgZN0lxbn06mZxIY9Pvt5NZZiy/kvwBzZOJeX64A5n72PMCVyN61d6QLWzsYaH+KC/SNoRF4wZo2T8KVpdHcHHzRbCu+B1fy6+AJXIBv/7FIbAJGWDbuHJ6w6mV3/T9lt4yL2I7h51kpz6H9gYhZN9biA7DzrRMmYHLVcEgVMhwRdUaEKX64cpDFvC2VMqrdkyBo9iHVwfeBCe7ZbxmlRKc9YzZxfI6uQw9YNfps+TWdpndbyjIo/w+vtOwn97NvoRrD28jz8RKXJe+D97zz8H1MVvBSyRHb6/14D1RwmJhNIlVWexjvI58qhLYd9SW/I5k4oYuT5CkxOPGWhvwj5RgQK4ObPIQYeDuIQiyMsPgkHYInp7AzU6lsPm2CYdZt1FY6xiHq0sookDFW3qzKDK9hj9UJlBUTB5HKzYSSKpxa0Y8bBPm4kdSCcQYJ2GsWASxoxEotTMD6QUPlOlOgKzMGuOGrkJ8rhsnXByjj+VW/Em5ihJD1IzZNfSpE/GOxDzaad7Cu/yTaZe6D+UuuSDvbcYkiyRIUh7H5MkI+ExxAD/v9oCUVCnurbOG1Cgf3PedAGZpaf+/6szW1npJq9GcUQgEGs35Ji0djab+tED/X89cjJ7bdIMkWODtNUPQDKEzBAQ/+29aM33ufwDqGr+cDAUAAA==", "America/Santiago": "H4sIAPygLGgC/82T60/NARjHf+ecbtRRKZeOWy4ljvKk6JTKI6WicuieUy5Zd910cTlIG4pNtMwMa+5qxlMu1dR6huQSzhlnYTWbKWNWy53UcbJ65R/w/e7zeZ4975+IuNQk4d+YDTOUyuHdtsigMggMOKHqUlaq37ScFnKYEgpbagp9sHapoLkWk83XZ7grb3iew5uSZE2drJ3r3p5Q1g+ouKHVXtk2ORPbMt5pnnWU8fMJOtC5RbKuoBwHtN44WP6L9G2PWcjtIFG+ksUYTJLIBWxkLydj31VoIkjJ1LwRTV/3ktmgDY5q1tLozq9ofqkHLJraUVqigTGnGtAypRas9unYOqgCxibVsY1TAdguP87jrMtpvOMOHt+XRxNN4nmiNorsupewrEZBk56qcPIRGU256otTs3/TtDJ7tN8tgelZYpzh2Q8zw97iLLtOcFAI7PCzGRw//eDZL0+D0/e7POd2E81tv8DyM5U0r66EnYv3kMuxNJ6/MZGgaD+6+gXQgvWp6ObTDu64Ehea+8MiaT16mOhIIVii4pEZeL6Xs1f1B1j8QMreB9rA51Iv+6ZdgSUlWsbwh7Q05Rr7uV2mZUFH2d/mEAW41mLA52wKtK7AwF4xBPUVYHBjFqzQxuDKeoFCarww9J4phCmLedXJK6T0e8mr1YdpjfwbhqtyKcL8BUZ7dEP01Y8cO+E+xJY94bjv1bA2i1hVlUzxeWpOKA2mdREJvD5VThvckTcGSylxSjxucuqlTV+MOGmsBSR1Tsfkvh5IaZJgqlYDaSe7ML2mFjLUrbj5SAVkqqowaztRtvdBzIkrp1yHi7zFK4/yjEs5XxZF+V3pXPBLQYUtobz1lYy2nZ/P2+94wI691qw+awc7M11wV3E/7A6zQpFYJBEZiUcqEUuMDTYx/U+q1zfdEoS/NtLrG0gw0+tbWbAYsshgnUZkNeKhe0hohBBuwBkWGnA34Db8bSLRyPwDypv37ZsDAAA=", "Asia/Tokyo": "H4sIAPygLGgC/wuJykxjwAQsUAwCnFA2TwOQuG7HVHD9beSHGz9+Fdw8a/3hNjvDh9trZT/cefbow92e/x+YGZkgkIGhmRmku2cBI1Bz3QQGDgjp4xvC4OUCxMEhIGlGEAYAoyLFToUAAAA=", "Australia/Sydney": "H4sIAPygLGgC/82S2y8VAADGvxOmI5eUuVNIHJVLRUch90su4RzXopPLcenCcXKrnL7Q1BaiByYTmumhIq2RnSVls3JbPXQRmV4atVkvlUnF8tgf0Pdtv+/7A37S5Bw5/h3Nta1Z+/pcQXPUUzarXTAifYCR4UyO9sZzrDOE461KTFSJqJHvSU09S2hFW1Drm5jaLsvUfm1OocEMhQ9/UmdhkBtumkH37QfoqZag3/cEBqnT2NjYDkOfAWwqqcRm6zYYJcph9KsCxuJQmOheoalNBk2HL9JcEEzzznRazDrSsiqIVoM6tC5t5paGHmxNUtGG47T1vwG7nM/YZlsG+7Ax2C/Mw0HUBYeJUYiEdRB13YPTnBI7Gl9w56ta7iq5Q+ceBV0Sa+haL6FbSjJ3F7hzj7cX98aa0N3Kmh5ui/RYBsUWxhBPfaRn5xz3q4d4YHISXh2z8O5Xw+fSMxxsaoFvZgf8KvrpH1SFgPRmBjrfYlCAisFa4QixkzHkeztCP11H2JtKHBouRHivHBGdCYhsCEVUlScOFzshOj+OMbJgxkbvo8TXkVJXM8Zt1WG8wRLjf39hwsI0E2fGmTQxwOSBbh7pm8LR22NIaXyM1MtdOFbSCll2HY4nliMtVIl0cQYyHOOQaRoMuaGCWYI0Zn2VMHs2kDkv3Zk7uJ0n7pvwZNt6nrq2yNOcZ17+e+bnakOR9AMFYXNQek7ijGgEhWZqFAnvomixBcVztSh5R5Q+V+DsozSc66nm+XYVy+rzqCqX8UJBDDUE6/6jAtVDq1o3dQtWrL7aCuFfRkRK4RcUuAqJFBAI8Ac6VUXKHAMAAA==", "Europe/Dublin": "H4sIAPygLGgC/82UfTTVBxzGfyaFxJd5W8i3mcTEZdVkmUllt7jzcld3zGSLau4aZo6bmXW2teU4zrcdm5msrzJMkkKJWsS8nJlsotKUUnnNW5nXq93M2T/7d3/sec7znM8fz9+PNHBPuPBvac3nie7Os+EnqspYUXwoo22x/uHLIs7MrubvD2fykbSlzJ+XY1bsDB8NO4zH4us5W1LGP7hPY471Dsy1qcU8O3vM65/gfKGF81uN8HjvMBbUyfFEw+9YmCvBk6zgoi9EeOqrZj4d6c3F0ae5xNeBS8WBeEYEfNY5lsv0RvmcgYzPDV3h8l4BK66N4Pkb2/FCWQv+dGqWL35bipUZZlgVl4aX9imxWqbAGr9s/tklCGtdq7BO1sZ17Vp8RdyJrcuWc5ukAK/ar8RrDil4bfJrbNeNxPb+Abxxz4T/+KUJO2om+WZJH98qNMbO1Ea+Hf0q34mIwS5/O74rJb7nrMP33U5gt5kt9hhKuWd6MfYqo7Cv/QH2dwTgQPllfFA8xYPfncKh/bt4+EgCjoSKeTQxBB9uCcdHIR44tnwJ/+luhePCEE9YauBE5288OduNU5XFPN2jzjPxx1lZVxGpHlmLC2xlqOGbhwu1XHGRKAkX9ZqjFshRq34WtYcluPj0UtZpFuGSQzOsW2SAelE3GdIdWN+vkg0UwE87HWVD2SgbWfWTsUstmaj/SqameWTadZKemUiipdWHyOx2LpgXFIJF1UFYlkxgmRUBKI+G5ft94FlvKViFOsJz9mvBestWWqFjCjZ2q8hmbDXZauuRbasx2fWO0PMlE2Tf0EKrUtvJ4cdScow5T6KDaeQUfB2co0vgBbcKWO3/DayxyIS1znGwVpkILmap5NIRCuumY8n1gie8dENG63NCyK3ClV4+4EHuGeb0SrgVeXy2DjZs1iDPnWaw0bqbNnkqYbNGA3lZ3QKvwfsgVq8CcVM9bOk6BlsL88G78SL5pCSDpCCLXtu7F3yTPyW/7UnkLw+jgBflJPX2otdNJLTN3pa2jYtIZrQZZFcN6I2xlRB45hEFtWrDm6wPwSUD8FbiQwhJbYIdIa0QmtBHb7ufhXeCG2mnZTqEuRVSuGYp7bIg2tWTRruV0bSnXkHvdkgpIi+I5LVR8N6XbrQ3JwDe321JkQfWQJTfeogON4EPnJZBzKZJ+FBfgFhHI4odvgNxuuMU11wDisHrtK8oB+KbKuij9EuUUJhJHyuyKTElkdSeWqD+jzX+a2suXPQ/8OPHU3qCMNcLBEHTUk1TEHRBTWfumWCONZ+g2hwLmn+3t49U2KiKOEAqbFDFS8WqzZzmX00FfwFmme46/AQAAA==", "Europe/Lisbon": "H4sIAPygLGgC/61UfTSWdxh+jLdS6MZ81EueemdiNkLCmEmY+SreQmUKoZKe3jBa5VnMmhznztRWWI+P1DGhIoymfITIV7Oi5I3la+LXZJhZI23VtrOzP3Zd57rP9bvu+/z+vIQbt/tTf4fsM83g/jPPZ6dHQk88m+Swi0n6rZpNTp5kU2qjmK8O6lGnsi4RztuHTT0ywKRZ9bLpwbuZDAGfOu2SRrJ4w0xWrzc5V3uG5JwRkFzOhcn7lEfOf7aTXGCWMRdFh5n8tVJMoYEjU7Swhil6UswUD2cxpTWF5HLRWfLtKW+m7MtYcuUkIVfDg0h5oBep8HAmlZY8pspEn1wzO06qPbKZ6rZOplayhal9RDPXu3xIXYErqRtMF9ezDuL6u2nkxjEjcqPCYUuDKE3cUFXGNIYqk8bsAHGTa7S46XQq0ywcJ81x9uIWA39xyydRzE3PSvKdfQFpNW2mv9cup28tukjfls6gb08co9v6Y+j2tg/pO7WB9N1iT7rjQjR3Ly2U60zw58SH3Ln7ove4Lh9TrttVh/thNZ97YCDD9Syd4nr52nTfgsV03+QCun/gV3qg/SH94/V79OA3jfTDrCv00Mnz9HBsGk32fU4/2hFN/+Sby424cdxj66PcqOEh7mfBXm5M0Y8bl1zPjY/YchPdqziZr3Uo2SQ+JXdEhloYbYMQYozyflqoIFRFRac18KrhL6gk6GCVFRtYFckyVmUkj1XtTmUX3UxgF1dEsfzSXEotm6PUk49SS+IQNPZ/DHSQCJZu9oVljkIQmNvAa7rGoKmmBa/LqIIWzxq1Ro1w+QNN1G5VRp2qufhG/jjqZvTjm4nt+FZ0HeqFlKK+3zlc4dUGBqJ8MLQoASPX47BSPQWMDcLBeCoSTPiJaNKxFUwnw9DssjW8fccDzTO90aLEDN+JsULLJDV811+AVtGmsNqWh9Z+fFij2Ys21lNgy6tFO0En2A31gL3kVbBvqIH3u9PBIScLHOvL0Ck+DpyzU9ElOBjWxkXhOvdYdA3ahm6rglDoaIfrVZxxg642bhjTRw8lW/C4pYCeo8th46XHuKl1Pmzm5MErfxA+iBwB78QG2OLdClsPDKCPZSH4etWjn8YJ2GaRg/7zCjBAHTGg7wsMnBLh9poI3NEhxJ1nN2HQtT2w67AFBme6we5ADWRiVsKedeYg8leBvSuWQIjNBITKUxCmp4RhpAvC5cYwvKkSIobacF9eJnzUUIL7T5TjgZwUPBiRgZHxkUjNkXjlOSWl/pW8v+i/cu4/fDxvzguUnv+UL2X/E588GfOdaR05kJB6Wj/SL3s1WkL2eU4p/LGd9dNb5RfvHZ2ElLuN28yY0fTL2mZG08k0JP7EbNNJzCa/A6jkV2IUBQAA", "Europe/London": "H4sIAPygLGgC/71UfzQVBhR+b89LJC7LjyGuGfZMvKxMykwqU3oLb/ViJauUeTPezLyaWWdbW47Tue3YrGHdymTSK79K1EoaKon0rJhIq0hFqkV6LKfa2Tn9s/2z7zv3u9+999x/P3l4TLTgWYx/UmMYeOJNP3skWc57OKtFjNlnpJyTW80/Zufwtkxr5i8rcHvSQ96xOht3rq/jXFk5/+Q3jHlOK3CXSw3mu7phfu8gFwiauUBrjrt7+rGwVol7TpxFzS4Z7mU17/tKikXfNHJxfDCXqIq5dJE7lwWF434p8AHPJC43GeCDZgo+2HeOK3oEWHn+Nh5qW4KHy5vxl6IRPvJ9GR7NssGq5Ew8tk6H1Qo1Hg/J5V+9I7DGpwprFS1c22rAJy2c6WTmUjrVZEf1H8+k00UCalihgDPURY1xy6lJZQFNw55wNmYEm1dK+FxQJ2rtHFg7W0fajk5okRViy4iIz7tvxvND32KrcTy29t7AtiuW/PupBmw/PsQXS69zh8YCOzPq+ZLqTe6KTcTLoa78h5z4iqcRX/Xdg9dsJNg9Sc7dwxOwR5eA11tvYm97GN6oOIM3Sx7wrR+KsG/DGu7floK3o4J4IDUS78yPxruR/njPYSL/6eeI9wV9PGgvxsHOJh4auYYPjpbwcLeIH67fzbraynhRfA3qSRQoXpSP4wx8UF+ahvo9tmgASjSoG0HDfhlOKLZmo0YpTtzykI33maFJwkWGre5sGnKUzdTAz0/dwZMUA2zu2EsW3jVkKTpNVlb5ZHV5L70wmEbW1VvI5tIusC3UwOSqTWCXTmC/PRZQqQKHDQvhxWA5OEZ5wEtuXuA0fwE5G1mBi+sUcrk3jSSGJiTRWpBrz216pXSQ3E4005SMVnL/uYw8Eg+RdFMmTV12ATxVpfCqbyVMC/0Opk/OAS/PZPDSpYK3TQZ5t0fBjOEk8jkcADPbFDQrL5J8K33o9Y3+5JdlS29EO5L/FzNg9jwxBayygTlO12hugA7miU9QoGMHBN66CkGiKghqqIP5l3fCAk0BBNcfoYWb00FWuJ3eiouDRemfU8iSNApVrqaw15QkDw6kty1ltNhNQovvS0lhPg8Uv5nR0nsvQ/j+uxShNYR32BSWld6A5al3IDKjAVZEaiEq5Tq963cAVi6rp1X2W2G1r4aix5fRmslEa7ozaa1ORTF1anqvXU6x+RGkrEmA97/2pbi8MPhgrT3Fb5wOCSGzQBVtCR9OtYPEuUPwkakAkjzMKam/C5KN71Ny43FQ37pA6/blwfqGSvpk6zFK0eTQp+pcSt2cSnrC5/4jRX/z8fTvP8X6zy7H6f/fHB0dLRuLMmMQ6j3NN1sUGj31xiDQ++c1eKFcMDtMLggc63MeGYFQKByTx4koFP4Fm8+zuzcFAAA=", "Pacific/Kiritimati": "H4sIAPygLGgC/wuJykxjwA+YgZgFiIUaQEToJwZ9Vu0FjEzM///nAEX+/88CSv//X5zAwMXAcOQBA5+PbwiDrqGBiQGIZNA2NGEAAOk8Wg9lAAAA" }python_dateutil-4.0.0/.gitignore0000644000000000000000000000054413615410400013642 0ustar00# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # Build detritus build/ dist/ .eggs *.egg-info/ # Test detritus .tox/ .pytest_cache/ venv/ .venv/ .hypothesis/ # Autogenerated version information src/dateutil/_version.py # Sphinx documentation docs/_build/ docs/docs_venv # Timezone information tzdata*.tar.gz .idea .cache .mypy_cache python_dateutil-4.0.0/AUTHORS.md0000644000000000000000000001556713615410400013334 0ustar00This is a (possibly incomplete) list of all the contributors to python-dateutil, initially generated from the git author metadata. The details of their specific contributions can be found in the git history. Prior to 2017-12-01, the library was licensed solely under the BSD 3-clause license, all contributions on or after 2017-12-01 are dual-licensed between Apache 2.0 and BSD 3-clause. In the list below, anyone whose name is marked with **R** has agreed to re-license their previously submitted code under Apache 2.0. Anyone whose name is marked with a **D** has only made contributions since the switch, and thus all their contributions are dual-licensed. ## Contributors (alphabetical order) - Aarni Koskela **D** - Adam Chainz - Adrien Cossa - Alec Nikolas Reiter - Alec Reiter - Aleksei Strizhak (gh: @Mifrill) - Alex Chamberlain (gh: @alexchamberlain) **D** - Alex Verdyan - Alex Willmer (gh: @moreati) **R** - Alexander Brugh (gh: @abrugh) - Alexander Shadchin (gh: @shadchin) **D** - Alistair McMaster (gh: @alimcmaster1 ) **D** - Allison Quinlan (gh: @aquinlan) **D** - Andrew Bennett (gh: @andrewcbennett) **D** - Andrew Murray - Arclight (gh: @arclightslavik) - Aritro Nandi (gh: @gurgenz221) **D** - Bernat Gabor (gh: @gaborbernat) **D** - Bradlee Speice (gh: @bspeice) **D** - Brandon W Maister - Brock Mendel (gh: @jbrockmendel) **R** - Brook Li (gh: @absreim) **D** - Carlos - Cheuk Ting Ho (gh: @cheukting) **D** - Chris van den Berg (gh: bergvca) **D** - Christopher Cordero (gh: cs-cordero) **D** - Christopher Corley - Claudio Canepa - Corey Girard (gh: @coreygirard) **D** - Cosimo Lupo (gh: @anthrotype) **D** - Daniel Lemm (gh: @ffe4) **D** - Daniel Lepage - David Lehrian - Dean Allsopp (gh: @daplantagenet) **D** - Dominik Kozaczko - Elliot Hughes (gh: @ElliotJH) **D** - Elvis Pranskevichus - Fan Huang (gh: @fhuang5) **D** - Florian Rathgeber (gh: @kynan) **D** - Gabriel Bianconi (gh: @GabrielBianconi) **D** - Gabriel Poesia - Gökçen Nurlu (gh: @gokcennurlu) **D** - Grant Garrett-Grossman (gh: @FakeNameSE) **D** - Gustavo Niemeyer (gh: @niemeyer) - Holger Joukl (gh: @hjoukl) - Hugo van Kemenade (gh: @hugovk) **D** - Igor - IonuÈ› Ciocîrlan - Jacqueline Chen (gh: @jachen20) **D** - Jairo Llopis (gh: @yajo) **D** - Jake Chorley (gh: @jakec-github) **D** - Jakub Kulík (gh: @kulikjak) **D** - Jan Studený - JAY (gh: @Jay1023CN) **D** - Jay Weisskopf (gh: @jayschwa) **D** - Jitesh - John Purviance (gh @jpurviance) **D** - Jon Dufresne (gh: @jdufresne) **R** - Jonas Neubert (gh: @jonemo) **R** - Jordi Masip (gh: @masipcat) - Juan Arias (gh: @jdarias3) **D** - Kevin Nguyen **D** - Kirit Thadaka (gh: @kirit93) **D** - Kubilay Kocak - Laszlo Kiss Kollar (gh: @lkollar) **D** - Lauren Oldja (gh: @loldja) **D** - Luca Ferocino (gh: @lucaferocino) **D** - Mario Corchero (gh: @mariocj89) **R** - Mark Bailey **D** - Mateusz Dziedzic (gh: @m-dz) **D** - Matt Cooper (gh: @vtbassmatt) **D** - Matthew Schinckel - Max Shenfield - Maxime Lorant - Michael Aquilina (gh: @MichaelAquilina) - Michael J. Schultz - Michael Käufl (gh: @michael-k) - Mike Gilbert - Nicholas Herrriot **D** - Nicolas Évrard (gh: @nicoe) **D** - Nick Smith - Nor.na (gh: @Master-Norna) **D** - Orson Adams (gh: @parsethis) **D** - Paul Brown (gh: @pawl) **D** - Paul Dickson (gh @prdickson) **D** - Paul Ganssle (gh: @pganssle) **R** - Pascal van Kooten (gh: @kootenpv) **R** - Pavel Ponomarev - Peter Bieringer - Pierre Gergondet (gh: @gergondet) **D** - Quentin Pradet - Raymond Cha (gh: @weatherpattern) **D** - Ridhi Mahajan **D** - Robin Henriksson Törnström **D** - Rowan Walsh (gh: @rowan-walsh) **D** - Roy Williams - Rustem Saiargaliev (gh: @amureki) **D** - Satyabrat Bhol (gh: @Satyabrat35) **D** - Savraj - Sergey Vishnikin - Sherry Zhou (gh: @cssherry) **D** - Siping Meng (gh: @smeng10) **D** - Stefan Bonchev **D** - Thierry Bastian - Thomas A Caswell (gh: @tacaswell) **R** - Thomas Achtemichuk - Thomas Grainger (gh: @graingert) **D** - Thomas Kluyver (gh: @takluyver) - Tim Gates (gh: timgates42) - Tomasz Kluczkowski (gh: @Tomasz-Kluczkowski) **D** - Tomi Pieviläinen - Unrud (gh: @unrud) - varun netrakar (gh: @varun3257) **D** - Xavier Lapointe (gh: @lapointexavier) **D** - X O - Yaron de Leeuw (gh: @jarondl) - Yoney **D** - Yuan Huang (gh: @huangy22) **D** - Zbigniew JÄ™drzejewski-Szmek - bachmann - bjv (@bjamesvERT) - friskysaga (gh: @kevinkt1) **D** - gl - gfyoung **D** - Labrys (gh: @labrys) **R** - ms-boom - ryanss (gh: @ryanss) **R** Unless someone has deliberately given permission to publish their e-mail, I have masked the domain names. If you are not on this list and believe you should be, or you *are* on this list and your information is inaccurate, please e-mail the current maintainer or the mailing list (dateutil@python.org) with your name, e-mail (if desired) and GitHub (if desired / applicable), as you would like them displayed. Additionally, please indicate if you are willing to dual license your old contributions under Apache 2.0. python_dateutil-4.0.0/LICENSE0000644000000000000000000000551113615410400012656 0ustar00Copyright 2017- Paul Ganssle Copyright 2017- dateutil contributors (see AUTHORS file) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. The above license applies to all contributions after 2017-12-01, as well as all contributions that have been re-licensed (see AUTHORS file for the list of contributors who have re-licensed their code). -------------------------------------------------------------------------------- dateutil - Extensions to the standard Python datetime module. Copyright (c) 2003-2011 - Gustavo Niemeyer Copyright (c) 2012-2014 - Tomi Pieviläinen Copyright (c) 2014-2016 - Yaron de Leeuw Copyright (c) 2015- - Paul Ganssle Copyright (c) 2015- - dateutil contributors (see AUTHORS file) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The above BSD License Applies to all code, even that also covered by Apache 2.0.python_dateutil-4.0.0/pyproject.toml0000644000000000000000000000722713615410400014573 0ustar00[build-system] requires = ["hatchling>=1.27", "hatch-vcs>=0.4", "hatch-fancy-pypi-readme>=24.1"] build-backend = "hatchling.build" [project] name = "python-dateutil" description = "Extensions to the standard Python datetime module" dynamic = ["version", "readme"] requires-python = ">=3.11" dependencies = ["tzdata"] license = "BSD-3-Clause" license-files = ["LICENSE", "AUTHORS.md"] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", "Programming Language :: Python :: Free Threading :: 2 - Beta", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries", ] [[project.authors]] name = "Gustavo Niemeyer" email = "gustavo@niemeyer.net" [[project.maintainers]] name = "Paul Ganssle" email = "dateutil@python.org" [project.urls] Homepage = "https://github.com/dateutil/dateutil" Documentation = "https://dateutil.readthedocs.io/en/stable/" Source = "https://github.com/dateutil/dateutil" [tool.towncrier] package = "dateutil" package_dir = "dateutil" filename = "NEWS" directory = "changelog.d" title_format = "Version {version} ({project_date})" issue_format = "GH #{issue}" template = "changelog.d/template.rst" [[tool.towncrier.type]] directory = "data" name = "Data updates" showcontent = true [[tool.towncrier.type]] directory = "deprecations" name = "Deprecations" showcontent = true [[tool.towncrier.type]] directory = "feature" name = "Features" showcontent = true [[tool.towncrier.type]] directory = "bugfix" name = "Bugfixes" showcontent = true [[tool.towncrier.type]] directory = "doc" name = "Documentation changes" showcontent = true [[tool.towncrier.type]] directory = "misc" name = "Misc" showcontent = true [tool.black] line-length = 80 [tool.isort] atomic=true force_grid_wrap=0 include_trailing_comma=true known_first_party = ["dateutil"] known_third_party=[ "pytest", "hypothesis", "freezegun", ] multi_line_output=3 use_parentheses=true [tool.pytest.ini_options] python_files = [ "test_*.py", "*_test.py", "*_solution.py", ] xfail_strict = true filterwarnings = [ "error", "error::DeprecationWarning", "error::PendingDeprecationWarning", ] markers = [ "gettz", "import_star", "isoparser", "parserinfo", "rrule", "rruleset", "rrulestr", "smoke", "tz_resolve_imaginary", "tzdata_properties", "tzfile", "tzlocal", "tzoffset", "tzstr", ] [tool.hatch.version] source = "vcs" [tool.hatch.build.hooks.vcs] version-file = "src/dateutil/_version.py" [tool.hatch.build.targets.wheel] packages = ["src/dateutil"] [tool.hatch.build.targets.sdist] exclude = [ "/AGENTS.md", "/RELEASING", "/.github", "/.gitattributes", "**/.gitignore", "/.readthedocs.yml", "/.pre-commit-config.yaml", "/codecov.yml", ] [tool.hatch.metadata.hooks.fancy-pypi-readme] content-type = "text/x-rst" [[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] path = "README.rst" [[tool.hatch.metadata.hooks.fancy-pypi-readme.substitutions]] pattern = "(?m)^\\.\\. doctest[^\\n]*" replacement = ".. code-block:: python3" python_dateutil-4.0.0/PKG-INFO0000644000000000000000000001625513615410400012755 0ustar00Metadata-Version: 2.5 Name: python-dateutil Version: 4.0.0 Summary: Extensions to the standard Python datetime module Project-URL: Homepage, https://github.com/dateutil/dateutil Project-URL: Documentation, https://dateutil.readthedocs.io/en/stable/ Project-URL: Source, https://github.com/dateutil/dateutil Author-email: Gustavo Niemeyer Maintainer-email: Paul Ganssle License-Expression: BSD-3-Clause License-File: AUTHORS.md License-File: LICENSE Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 Classifier: Programming Language :: Python :: 3.15 Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Software Development :: Libraries Requires-Python: >=3.11 Requires-Dist: tzdata Description-Content-Type: text/x-rst dateutil - powerful extensions to datetime ========================================== |pypi| |support| |licence| |gitter| |readthedocs| |gha| |coverage| .. |pypi| image:: https://img.shields.io/pypi/v/python-dateutil.svg?style=flat-square :target: https://pypi.org/project/python-dateutil/ :alt: pypi version .. |support| image:: https://img.shields.io/pypi/pyversions/python-dateutil.svg?style=flat-square :target: https://pypi.org/project/python-dateutil/ :alt: supported Python version .. |gha| image:: https://github.com/dateutil/dateutil/actions/workflows/validate.yml/badge.svg :target: https://github.com/dateutil/dateutil/actions :alt: github actions build status .. |coverage| image:: https://codecov.io/gh/dateutil/dateutil/branch/master/graphs/badge.svg?branch=master :target: https://codecov.io/gh/dateutil/dateutil?branch=master :alt: Code coverage .. |gitter| image:: https://badges.gitter.im/dateutil/dateutil.svg :alt: Join the chat at https://gitter.im/dateutil/dateutil :target: https://gitter.im/dateutil/dateutil .. |licence| image:: https://img.shields.io/pypi/l/python-dateutil.svg?style=flat-square :target: https://pypi.org/project/python-dateutil/ :alt: licence .. |readthedocs| image:: https://img.shields.io/readthedocs/dateutil/latest.svg?style=flat-square&label=Read%20the%20Docs :alt: Read the documentation at https://dateutil.readthedocs.io/en/latest/ :target: https://dateutil.readthedocs.io/en/latest/ 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: .. code-block:: python3 >>> 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 in 2003. It is maintained by: * Gustavo Niemeyer 2003-2011 * Tomi Pieviläinen 2012-2014 * Yaron de Leeuw 2014-2016 * Paul Ganssle 2015- 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. 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. .. _6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB: https://pgp.mit.edu/pks/lookup?op=vindex&search=0xCD54FCE3D964BEFB