🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

python-dateutil

Package Overview
Dependencies
Maintainers
4
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

python-dateutil - pypi Package Compare versions

Comparing version
2.5.3
to
2.6.0
+18
.gitattributes
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Specify what's text and should be normalized
*.py text
*.in text
*.rst text
*.cfg text
*.ini text
*.yml text
*.json text
*.bat text
*.sh text
RELEASING text
# NEWS and Windows batch files should be crlf
NEWS eol=crlf
*.bat eol=crlf
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
build/
dist/
*.egg-info/
.tox/
# Sphinx documentation
docs/_build/
# Timezone information
tzdata*.tar.gz
language: python
python:
- "2.6"
- "2.7"
- "3.2"
- "3.3"
- "3.4"
- "3.5"
- "3.6-dev"
- "nightly"
- "pypy"
- "pypy3"
matrix:
# pypy3 latest version is not playing nice.
allow_failures:
- python: "pypy3"
- python: "3.6-dev"
- python: "nightly"
before_install:
# Travis version of Pypy is old and is causing some jobs to fail, so
# we should build this ourselves
- "export PYENV_ROOT=$HOME/.pyenv"
- |
if [ "$TRAVIS_PYTHON_VERSION" = "pypy" ]; then
export PYPY_VERSION="5.4.1"
source ./ci_tools/pypy_upgrade.sh
fi
# Install codecov
- if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install coverage==3.7.1; fi
- pip install codecov
install:
- pip install six
- if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi
- ./ci_tools/retry.sh python updatezinfo.py
cache:
directories:
- $HOME/.pyenv
- $HOME/.cache/pip
script:
- coverage run --omit=setup.py,dateutil/test/* setup.py test
after_success:
- codecov
sudo: false
build: false
environment:
matrix:
- PYTHON: "C:/Python27"
- PYTHON: "C:/Python27-x64"
- PYTHON: "C:/Python33"
- PYTHON: "C:/Python33-x64"
- PYTHON: "C:/Python34"
- PYTHON: "C:/Python34-x64"
- PYTHON: "C:/Python35"
- PYTHON: "C:/Python35-x64"
install:
# Add PostgreSQL (zic), Python and scripts directory to current path
- set path=c:\Program Files\PostgreSQL\9.3\bin\;%PATH%
- set path=%PATH%;%PYTHON%;%PYTHON%/Scripts
# If this isn't done, I guess Appveyor will install to the Python2.7 version
- set pip_cmd=%PYTHON%/python.exe -m pip
# Download scripts and dependencies
- ps: Start-FileDownload 'https://bootstrap.pypa.io/get-pip.py'
- "%PYTHON%/python.exe get-pip.py"
- "%pip_cmd% install six"
- "%pip_cmd% install coverage"
- "%pip_cmd% install codecov"
# This frequently fails with network errors, so we'll retry it up to 5 times
# with a 1 minute rate limit.
- "ci_tools/retry.bat %PYTHON%/python.exe updatezinfo.py"
# This environment variable tells the test suite it's OK to mess with the time zone.
- set DATEUTIL_MAY_CHANGE_TZ=1
test_script:
- "coverage run --omit=setup.py,dateutil/test/* setup.py test"
after_test:
- "codecov"
#!/usr/bin/env bash
# Need to install an upgraded version of pypy.
if [ -f "$PYENV_ROOT/bin/pyenv" ]; then
pushd "$PYENV_ROOT" && git pull && popd
else
rm -rf "$PYENV_ROOT" && git clone --depth 1 https://github.com/yyuu/pyenv.git "$PYENV_ROOT"
fi
"$PYENV_ROOT/bin/pyenv" install --skip-existing "pypy-$PYPY_VERSION"
virtualenv --python="$PYENV_ROOT/versions/pypy-$PYPY_VERSION/bin/python" "$HOME/virtualenvs/pypy-$PYPY_VERSION"
source "$HOME/virtualenvs/pypy-$PYPY_VERSION/bin/activate"
@echo off
REM This script takes a command and retries it a few times if it fails, with a
REM timeout between each retry.
setlocal EnableDelayedExpansion
REM Loop at most n_retries times, waiting sleep_time times between
set sleep_time=60
set n_retries=5
for /l %%x in (1, 1, %n_retries%) do (
call %*
if not ERRORLEVEL 1 EXIT /B 0
timeout /t %sleep_time% /nobreak > nul
)
REM If it failed all n_retries times, we can give up at last.
EXIT /B 1
#!/usr/bin/env bash
sleep_time=60
n_retries=5
for i in `seq 1 $n_retries`; do
"$@" && exit 0
sleep $sleep_time
done
exit 1
coverage:
status:
patch: false
changes: false
project:
default:
target: '80'
comment: false
"""
Common code used in multiple modules.
"""
class weekday(object):
__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
__hash__ = None
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)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 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
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../'))
# -- 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',
]
# 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 = '2016, 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 = 'default'
# 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
# "<project> v<release> 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 = ['_static']
# 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 <link> 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 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
======
easter
======
.. automodule:: dateutil.easter
:members:
:undoc-members:
dateutil 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
[http://www.cl.cam.ac.uk/~mgk25/iso-time.html 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 occurences.
.. 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")
<dateutil.rrule.rrule object at 0x...>
>>> rrulestr("""
... DTSTART:19970902T090000
... RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5
... """)
<dateutil.rrule.rrule object at 0x...>
>>> rrulestr("FREQ=DAILY;INTERVAL=10;COUNT=5", forceset=True)
<dateutil.rrule.rruleset object at 0x...>
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
... """)
<dateutil.rrule.rruleset object at 0x...>
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)
tzutc examples
--------------
.. doctest:: tzutc
>>> 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'
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(tzutc())
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`
* `EST5EDT,4,0,6,7200,10,0,26,7200,3600`
* `EST5EDT,4,1,0,7200,10,-1,0,7200,3600`
* `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
[http://www.python.org/doc/current/lib/module-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,4,1,0,7200,10,-1,0,7200,3600')
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, 1, 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
[http://www.python.org/doc/current/lib/datetime-tzinfo.html tzinfo documentation]
for more information.
tzfile examples
---------------
.. testsetup:: tzfile
from datetime import datetime
from dateutil.tz import tzfile, tzutc
.. 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(tzutc())
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
<tzicalvtz 'US-Eastern'>
>>> datetime.now(est)
datetime.datetime(2003, 10, 6, 19, 44, 18, 667987,
tzinfo=<tzicalvtz 'US-Eastern'>)
>>> 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
.. 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: 2
self
easter
parser
relativedelta
rrule
tz
zoneinfo
examples
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
@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 ^<target^>` where ^<target^> 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
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# 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 <target>' where <target> 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)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(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:
$(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:
$(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:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(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:
$(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:
$(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:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(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:
$(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:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(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:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
======
parser
======
.. automodule:: dateutil.parser
:members:
:undoc-members:
=============
relativedelta
=============
.. automodule:: dateutil.relativedelta
:members:
:undoc-members:
=====
rrule
=====
.. automodule:: dateutil.rrule
:members:
:undoc-members:

Sorry, the diff of this file is not supported yet

==
tz
==
.. automodule:: dateutil.tz
:members:
:undoc-members:
========
zoneinfo
========
.. automodule:: dateutil.zoneinfo
:members:
:undoc-members:
zonefile_metadata
-----------------
The zonefile metadata defines the version and exact location of
the timezone database to download. It is used in the :ref:`updatezinfo.py`
script. A json encoded file is included in the source-code, and
within each tar file we produce. The json file is attached here:
.. literalinclude:: ../zonefile_metadata.json
:language: json

Sorry, the diff of this file is not supported yet

[tox]
envlist =
py26,
py27,
py32,
py33,
py34,
py35,
py36
[testenv]
commands = python setup.py test -q {posargs}
deps =
py26: unittest2
six
+1
-1
# -*- coding: utf-8 -*-
__version__ = "2.5.3"
__version__ = "2.6.0"

@@ -36,5 +36,5 @@ # -*- coding: utf-8 -*-

EASTER_JULIAN = 1
EASTER_ORTHODOX = 2
EASTER_WESTERN = 3
* ``EASTER_JULIAN = 1``
* ``EASTER_ORTHODOX = 2``
* ``EASTER_WESTERN = 3``

@@ -41,0 +41,0 @@ The default method is method 3.

@@ -59,2 +59,6 @@ # -*- coding:iso-8859-1 -*-

if 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

@@ -61,0 +65,0 @@ self.charstack = []

@@ -11,36 +11,9 @@ # -*- coding: utf-8 -*-

__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"]
from ._common import weekday
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])
class weekday(object):
__slots__ = ["weekday", "n"]
__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"]
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 __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)
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])
class relativedelta(object):

@@ -73,3 +46,3 @@ """

the corresponding aritmetic operation on the original datetime value
with the information in the relativedelta.
with the information in the relativedelta.

@@ -304,3 +277,3 @@ weekday:

relativedelta(days=1, hours=14)
:return:

@@ -311,6 +284,6 @@ Returns a :class:`dateutil.relativedelta.relativedelta` object.

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)

@@ -354,4 +327,21 @@ minutes = int(minutes_f)

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):
raise TypeError("unsupported type for add operation")
return NotImplemented
elif self._has_time and not isinstance(other, datetime.datetime):

@@ -405,3 +395,3 @@ other = datetime.datetime.fromordinal(other.toordinal())

if not isinstance(other, relativedelta):
raise TypeError("unsupported type for sub operation")
return NotImplemented # In case the other object defines __rsub__
return self.__class__(years=self.years - other.years,

@@ -463,3 +453,7 @@ months=self.months - other.months,

def __mul__(self, other):
f = float(other)
try:
f = float(other)
except TypeError:
return NotImplemented
return self.__class__(years=int(self.years * f),

@@ -486,3 +480,3 @@ months=int(self.months * f),

if not isinstance(other, relativedelta):
return False
return NotImplemented
if self.weekday or other.weekday:

@@ -512,2 +506,4 @@ if not self.weekday or not other.weekday:

__hash__ = None
def __ne__(self, other):

@@ -517,4 +513,9 @@ return not self.__eq__(other)

def __div__(self, other):
return self.__mul__(1/float(other))
try:
reciprocal = 1 / float(other)
except TypeError:
return NotImplemented
return self.__mul__(reciprocal)
__truediv__ = __div__

@@ -521,0 +522,0 @@

@@ -19,5 +19,7 @@ # -*- coding: utf-8 -*-

from six import advance_iterator, integer_types
from six.moves import _thread
from six.moves import _thread, range
import heapq
from ._common import weekday as weekdaybase
# For warning about deprecation of until and count

@@ -62,34 +64,12 @@ from warnings import warn

class weekday(object):
__slots__ = ["weekday", "n"]
def __init__(self, weekday, n=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")
raise ValueError("Can't create weekday with n==0")
self.weekday = weekday
self.n = n
super(weekday, self).__init__(wkday, 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 __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)
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])

@@ -712,3 +692,3 @@

if self._wkst:
parts.append('WKST=' + str(self._wkst))
parts.append('WKST=' + repr(weekday(self._wkst))[0:2])

@@ -757,2 +737,17 @@ if self._count:

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

@@ -759,0 +754,0 @@ year, month, day, hour, minute, second, weekday, yearday, _ = \

@@ -8,4 +8,8 @@ from __future__ import unicode_literals

import os
import datetime
import time
import subprocess
import warnings
import tempfile
import pickle

@@ -61,21 +65,83 @@

class TZWinContext(object):
""" Context manager for changing local time zone on Windows """
class PicklableMixin(object):
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, 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 compares
equal to the original object, but is not the same object.
"""
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)
self.assertIsNot(obj, nobj)
self.assertEqual(obj, nobj)
class TZContextBase(object):
"""
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):
# Allowing dateutil to change the local TZ is set as a local environment
# flag.
return bool(os.environ.get('DATEUTIL_MAY_CHANGE_TZ', False))
"""
Class method used to query whether or not this class allows time zone
changes.
"""
guard = bool(os.environ.get(cls._guard_var_name, False))
def __init__(self, tzname):
self.tzname = tzname
self._old_tz = None
# _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():
raise ValueError('Environment variable DATEUTIL_MAY_CHANGE_TZ ' +
'must be true.')
raise ValueError(self.tz_change_disallowed_message())
self._old_tz = self.get_current_tz()
self.set_current_tz(self.tzname)
self.set_current_tz(self.tzval)

@@ -86,3 +152,44 @@ def __exit__(self, type, value, traceback):

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)

@@ -105,2 +212,81 @@

raise OSError('Failed to set current time zone: ' +
(err or 'Unknown error.'))
(err or 'Unknown error.'))
###
# Compatibility functions
def _total_seconds(td):
# Python 2.6 doesn't have a total_seconds() method on timedelta objects
return ((td.seconds + td.days * 86400) * 1000000 +
td.microseconds) // 1000000
total_seconds = getattr(datetime.timedelta, 'total_seconds', _total_seconds)
###
# Utility classes
class NotAValueClass(object):
"""
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
__div__ = __rdiv__ = _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(object):
"""
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(object):
""" Sentinel class for unset time zone variable """
pass
UnsetTz = UnsetTzClass()

@@ -21,3 +21,3 @@ from dateutil.easter import easter

date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 8), date(2013, 3, 31),
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),

@@ -84,3 +84,3 @@ date(2018, 4, 1), date(2019, 4, 21),

for easter_date in western_easter_dates:
self.assertEqual(easter_date,
self.assertEqual(easter_date,
easter(easter_date.year, EASTER_WESTERN))

@@ -87,0 +87,0 @@

@@ -10,3 +10,5 @@ # -*- coding: utf-8 -*-

import six
from six import assertRaisesRegex, PY3
from six.moves import StringIO

@@ -34,2 +36,70 @@ class ParserTest(unittest.TestCase):

def testNone(self):
with self.assertRaises(TypeError):
parse(None)
def testInvalidType(self):
with self.assertRaises(TypeError):
parse(13)
def testDuckTyping(self):
# We want to support arbitrary classes that implement the stream
# interface.
class StringPassThrough(object):
def __init__(self, stream):
self.stream = stream
def read(self, *args, **kwargs):
return self.stream.read(*args, **kwargs)
dstr = StringPassThrough(StringIO('2014 January 19'))
self.assertEqual(parse(dstr), datetime(2014, 1, 19))
def testParseStream(self):
dstr = StringIO('2014 January 19')
self.assertEqual(parse(dstr), datetime(2014, 1, 19))
def testParseStr(self):
self.assertEqual(parse(self.str_str),
parse(self.uni_str))
def testParserParseStr(self):
from dateutil.parser import parser
self.assertEqual(parser().parse(self.str_str),
parser().parse(self.uni_str))
def testParseUnicodeWords(self):
class rus_parserinfo(parserinfo):
MONTHS = [("янв", "Январь"),
("фев", "Февраль"),
("мар", "Март"),
("апр", "Апрель"),
("май", "Май"),
("июн", "Июнь"),
("июл", "Июль"),
("авг", "Август"),
("сен", "Сентябрь"),
("окт", "Октябрь"),
("ноя", "Ноябрь"),
("дек", "Декабрь")]
self.assertEqual(parse('10 Сентябрь 2015 10:20',
parserinfo=rus_parserinfo()),
datetime(2015, 9, 10, 10, 20))
def testParseWithNulls(self):
# This relies on the from __future__ import unicode_literals, because
# explicitly specifying a unicode literal is a syntax error in Py 3.2
# May want to switch to u'...' if we ever drop Python 3.2 support.
pstring = '\x00\x00August 29, 1924'
self.assertEqual(parse(pstring),
datetime(1924, 8, 29))
def testDateCommandFormat(self):

@@ -743,41 +813,2 @@ self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",

def testParseStr(self):
self.assertEqual(parse(self.str_str),
parse(self.uni_str))
def testParserParseStr(self):
from dateutil.parser import parser
self.assertEqual(parser().parse(self.str_str),
parser().parse(self.uni_str))
def testParseUnicodeWords(self):
class rus_parserinfo(parserinfo):
MONTHS = [("янв", "Январь"),
("фев", "Февраль"),
("мар", "Март"),
("апр", "Апрель"),
("май", "Май"),
("июн", "Июнь"),
("июл", "Июль"),
("авг", "Август"),
("сен", "Сентябрь"),
("окт", "Октябрь"),
("ноя", "Ноябрь"),
("дек", "Декабрь")]
self.assertEqual(parse('10 Сентябрь 2015 10:20',
parserinfo=rus_parserinfo()),
datetime(2015, 9, 10, 10, 20))
def testParseWithNulls(self):
# This relies on the from __future__ import unicode_literals, because
# explicitly specifying a unicode literal is a syntax error in Py 3.2
# May want to switch to u'...' if we ever drop Python 3.2 support.
pstring = '\x00\x00August 29, 1924'
self.assertEqual(parse(pstring),
datetime(1924, 8, 29))
def testNoYearFirstNoDayFirst(self):

@@ -784,0 +815,0 @@ dtstr = '090107'

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from ._common import unittest, WarningTestMixin
from ._common import unittest, WarningTestMixin, NotAValue
import calendar
from datetime import datetime, date
from datetime import datetime, date, timedelta
from dateutil.relativedelta import *
class RelativeDeltaTest(WarningTestMixin, unittest.TestCase):

@@ -36,3 +37,3 @@ now = datetime(2003, 9, 17, 20, 54, 47, 282310)

msg='Multiplication does not inherit type.')
self.assertEqual(type(ccRD / 5.0), type(ccRD),

@@ -195,2 +196,6 @@ msg='Division does not inherit type.')

def testAdditionUnsupportedType(self):
# For unsupported types that define their own comparators, etc.
self.assertIs(relativedelta(days=1) + NotAValue, NotAValue)
def testSubtraction(self):

@@ -215,2 +220,5 @@ self.assertEqual(relativedelta(days=10) -

def testSubtractionUnsupportedType(self):
self.assertIs(relativedelta(days=1) + NotAValue, NotAValue)
def testMultiplication(self):

@@ -222,2 +230,5 @@ self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=1) * 28,

def testMultiplicationUnsupportedType(self):
self.assertIs(relativedelta(days=1) * NotAValue, NotAValue)
def testDivision(self):

@@ -227,2 +238,5 @@ self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=28) / 28,

def testDivisionUnsupportedType(self):
self.assertIs(relativedelta(days=1) / NotAValue, NotAValue)
def testBoolean(self):

@@ -233,7 +247,7 @@ self.assertFalse(relativedelta(days=0))

def testComparison(self):
d1 = relativedelta(years=1, months=1, days=1, leapdays=0, hours=1,
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,
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,
d3 = relativedelta(years=1, months=1, days=1, leapdays=0, hours=1,
minutes=1, seconds=1, microseconds=2)

@@ -248,2 +262,5 @@

def testInequalityUnsupportedType(self):
self.assertIs(relativedelta(hours=3) == NotAValue, NotAValue)
def testInequalityWeekdays(self):

@@ -255,5 +272,5 @@ # Different weekdays

wday_tu = relativedelta(year=1997, month=4, weekday=TU)
self.assertTrue(wday_mo_1 == wday_mo_1)
self.assertFalse(no_wday == wday_mo_1)

@@ -264,3 +281,3 @@ self.assertFalse(wday_mo_1 == no_wday)

self.assertFalse(wday_mo_2 == wday_mo_1)
self.assertFalse(wday_mo_1 == wday_tu)

@@ -277,3 +294,3 @@ self.assertFalse(wday_tu == wday_mo_1)

self.assertEqual((rd.weeks, rd.days), (8, 8 * 7 + 6))
rd.weeks = 3

@@ -305,3 +322,3 @@ self.assertEqual((rd.weeks, rd.days), (3, 3 * 7 + 6))

relativedelta(year=2.86)
with self.assertWarns(DeprecationWarning):

@@ -496,1 +513,71 @@ relativedelta(month=1.29)

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)
from six import PY3
from six.moves import _thread
__all__ = ['tzname_in_python2']
from datetime import datetime, timedelta, tzinfo
import copy
ZERO = timedelta(0)
__all__ = ['tzname_in_python2', 'enfold']
def tzname_in_python2(namefunc):

@@ -18,2 +25,357 @@ """Change unicode output into bytestrings in Python 2

return adjust_encoding
return adjust_encoding
# The following is adapted from Alexander Belopolsky's tz library
# https://github.com/abalkin/tz
if hasattr(datetime, 'fold'):
# This is the pre-python 3.6 fold situation
def enfold(dt, fold=1):
"""
Provides a unified interface for assigning the ``fold`` attribute to
datetimes both before and after the implementation of PEP-495.
:param fold:
The value for the ``fold`` attribute in the returned datetime. This
should be either 0 or 1.
:return:
Returns an object for which ``getattr(dt, 'fold', 0)`` returns
``fold`` for all versions of Python. In versions prior to
Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
subclass of :py:class:`datetime.datetime` with the ``fold``
attribute added, if ``fold`` is 1.
..versionadded:: 2.6.0
"""
return dt.replace(fold=fold)
else:
class _DatetimeWithFold(datetime):
"""
This is a class designed to provide a PEP 495-compliant interface for
Python versions before 3.6. It is used only for dates in a fold, so
the ``fold`` attribute is fixed at ``1``.
..versionadded:: 2.6.0
"""
__slots__ = ()
@property
def fold(self):
return 1
def enfold(dt, fold=1):
"""
Provides a unified interface for assigning the ``fold`` attribute to
datetimes both before and after the implementation of PEP-495.
:param fold:
The value for the ``fold`` attribute in the returned datetime. This
should be either 0 or 1.
:return:
Returns an object for which ``getattr(dt, 'fold', 0)`` returns
``fold`` for all versions of Python. In versions prior to
Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
subclass of :py:class:`datetime.datetime` with the ``fold``
attribute added, if ``fold`` is 1.
..versionadded:: 2.6.0
"""
if getattr(dt, 'fold', 0) == fold:
return dt
args = dt.timetuple()[:6]
args += (dt.microsecond, dt.tzinfo)
if fold:
return _DatetimeWithFold(*args)
else:
return datetime(*args)
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 _fold(self, dt):
return getattr(dt, 'fold', 0)
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
occurence, chronologically, of the ambiguous datetime).
:param dt:
A timezone-aware :class:`datetime.dateime` object.
"""
# Re-implement the algorithm from Python's datetime.py
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")
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
# for pre-PEP 495 versions of python, we need to tweak the algorithm.
dtdst = dt.dst()
if dtdst is None:
raise ValueError("fromutc() requires a non-None dst() result")
delta = dtoff - dtdst
if delta:
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
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
occurance, chronologically, of the ambiguous datetime).
:param dt:
A timezone-aware :class:`datetime.dateime` 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
@tzname_in_python2
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 self._fold(dt)
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 __ne__(self, other):
return not (self == other)
def __repr__(self):
return "%s(...)" % self.__class__.__name__
__reduce__ = object.__reduce__
def _total_seconds(td):
# Python 2.6 doesn't have a total_seconds() method on timedelta objects
return ((td.seconds + td.days * 86400) * 1000000 +
td.microseconds) // 1000000
_total_seconds = getattr(timedelta, 'total_seconds', _total_seconds)

@@ -15,5 +15,12 @@ # -*- coding: utf-8 -*-

import os
import bisect
import copy
from operator import itemgetter
from contextlib import contextmanager
from six import string_types, PY3
from ._common import tzname_in_python2
from ._common import tzname_in_python2, _tzinfo, _total_seconds
from ._common import tzrangebase, enfold

@@ -25,11 +32,10 @@ try:

relativedelta = None
parser = None
rrule = None
ZERO = datetime.timedelta(0)
EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal()
EPOCH = datetime.datetime.utcfromtimestamp(0)
EPOCHORDINAL = EPOCH.toordinal()
class tzutc(datetime.tzinfo):
"""
This is a tzinfo object that represents the UTC time zone.
"""
def utcoffset(self, dt):

@@ -45,8 +51,29 @@ return ZERO

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, (tzutc, tzoffset)):
return NotImplemented
return (isinstance(other, tzutc) or
(isinstance(other, tzoffset) and other._offset == ZERO))
__hash__ = None
def __ne__(self, other):
return not self.__eq__(other)
return not (self == other)

@@ -60,5 +87,20 @@ def __repr__(self):

class tzoffset(datetime.tzinfo):
"""
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 = _total_seconds(offset)
except (TypeError, AttributeError):
pass
self._offset = datetime.timedelta(seconds=offset)

@@ -72,2 +114,18 @@

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

@@ -78,7 +136,11 @@ def tzname(self, dt):

def __eq__(self, other):
return (isinstance(other, tzoffset) and
self._offset == other._offset)
if not isinstance(other, tzoffset):
return NotImplemented
return self._offset == other._offset
__hash__ = None
def __ne__(self, other):
return not self.__eq__(other)
return not (self == other)

@@ -88,3 +150,3 @@ def __repr__(self):

repr(self._name),
self._offset.days*86400+self._offset.seconds)
int(_total_seconds(self._offset)))

@@ -94,4 +156,9 @@ __reduce__ = object.__reduce__

class tzlocal(datetime.tzinfo):
class tzlocal(_tzinfo):
"""
A :class:`tzinfo` subclass built around the ``time`` timezone functions.
"""
def __init__(self):
super(tzlocal, self).__init__()
self._std_offset = datetime.timedelta(seconds=-time.timezone)

@@ -103,5 +170,8 @@ if time.daylight:

self._dst_saved = self._dst_offset - self._std_offset
self._hasdst = bool(self._dst_saved)
def utcoffset(self, dt):
if dt is None:
return dt
if dt is None and self._hasdst:
return None

@@ -114,4 +184,7 @@ if self._isdst(dt):

def dst(self, dt):
if dt is None and self._hasdst:
return None
if self._isdst(dt):
return self._dst_offset-self._std_offset
return self._dst_offset - self._std_offset
else:

@@ -124,3 +197,25 @@ return ZERO

def _isdst(self, 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

@@ -150,15 +245,28 @@ # the hour near to a change is DST or not.

#
timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400
+ dt.hour * 3600
+ dt.minute * 60
+ dt.second)
return time.localtime(timestamp+time.timezone).tm_isdst
if not self._hasdst:
return False
# Check for ambiguous times:
dstval = self._naive_is_dst(dt)
fold = getattr(dt, 'fold', None)
if self.is_ambiguous(dt):
if fold is not None:
return not self._fold(dt)
else:
return True
return dstval
def __eq__(self, other):
return (isinstance(other, tzlocal) and
(self._std_offset == other._std_offset and
self._dst_offset == other._dst_offset))
if not isinstance(other, tzlocal):
return NotImplemented
return (self._std_offset == other._std_offset and
self._dst_offset == other._dst_offset)
__hash__ = None
def __ne__(self, other):
return not self.__eq__(other)
return not (self == other)

@@ -172,3 +280,4 @@ def __repr__(self):

class _ttinfo(object):
__slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt"]
__slots__ = ["offset", "delta", "isdst", "abbr",
"isstd", "isgmt", "dstoffset"]

@@ -189,3 +298,4 @@ def __init__(self):

if not isinstance(other, _ttinfo):
return False
return NotImplemented
return (self.offset == other.offset and

@@ -196,6 +306,9 @@ self.delta == other.delta and

self.isstd == other.isstd and
self.isgmt == other.isgmt)
self.isgmt == other.isgmt and
self.dstoffset == other.dstoffset)
__hash__ = None
def __ne__(self, other):
return not self.__eq__(other)
return not (self == other)

@@ -214,8 +327,40 @@ def __getstate__(self):

class tzfile(datetime.tzinfo):
class _tzfile(object):
"""
Lightweight class for holding the relevant transition and time zone
information read from binary tzfiles.
"""
attrs = ['trans_list', 'trans_idx', 'ttinfo_list',
'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first']
# http://www.twinsun.com/tz/tz-link.htm
# ftp://ftp.iana.org/tz/tz*.tar.gz
def __init__(self, **kwargs):
for attr in self.attrs:
setattr(self, attr, kwargs.get(attr, None))
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)``.
See `Sources for Time Zone and Daylight Saving Time Data
<http://www.twinsun.com/tz/tz-link.htm>`_ for more information. Time zone
files can be compiled from the `IANA Time Zone database files
<https://www.iana.org/time-zones>`_ with the `zic time zone compiler
<https://www.freebsd.org/cgi/man.cgi?query=zic&sektion=8>`_
"""
def __init__(self, fileobj, filename=None):
super(tzfile, self).__init__()
file_opened_here = False

@@ -233,2 +378,20 @@ if isinstance(fileobj, string_types):

if fileobj is not None:
if not file_opened_here:
fileobj = _ContextWrapper(fileobj)
with fileobj as file_stream:
tzobj = self._read_tzfile(file_stream)
self._set_tzdata(tzobj)
def _set_tzdata(self, tzobj):
""" Set the time zone data of this object from a _tzfile object """
# Copy the relevant attributes over as private attributes
for attr in _tzfile.attrs:
setattr(self, '_' + attr, getattr(tzobj, attr))
def _read_tzfile(self, fileobj):
out = _tzfile()
# From tzfile(5):

@@ -243,122 +406,116 @@ #

# of the value is written first).
try:
if fileobj.read(4).decode() != "TZif":
raise ValueError("magic not found")
if fileobj.read(4).decode() != "TZif":
raise ValueError("magic not found")
fileobj.read(16)
fileobj.read(16)
(
# The number of UTC/local indicators stored in the file.
ttisgmtcnt,
(
# The number of UTC/local indicators stored in the file.
ttisgmtcnt,
# The number of standard/wall indicators stored in the file.
ttisstdcnt,
# The number of standard/wall indicators stored in the file.
ttisstdcnt,
# The number of leap seconds for which data is
# stored in the file.
leapcnt,
# The number of leap seconds for which data is
# stored in the file.
leapcnt,
# The number of "transition times" for which data
# is stored in the file.
timecnt,
# The number of "transition times" for which data
# is stored in the file.
timecnt,
# The number of "local time types" for which data
# is stored in the file (must not be zero).
typecnt,
# The number of "local time types" for which data
# is stored in the file (must not be zero).
typecnt,
# The number of characters of "time zone
# abbreviation strings" stored in the file.
charcnt,
# The number of characters of "time zone
# abbreviation strings" stored in the file.
charcnt,
) = struct.unpack(">6l", fileobj.read(24))
) = struct.unpack(">6l", fileobj.read(24))
# The above header is followed by tzh_timecnt four-byte
# values of type long, sorted in ascending order.
# These values are written in ``standard'' byte order.
# Each is used as a transition time (as returned by
# time(2)) at which the rules for computing local time
# change.
# The above header is followed by tzh_timecnt four-byte
# values of type long, sorted in ascending order.
# These values are written in ``standard'' byte order.
# Each is used as a transition time (as returned by
# time(2)) at which the rules for computing local time
# change.
if timecnt:
self._trans_list = struct.unpack(">%dl" % timecnt,
fileobj.read(timecnt*4))
else:
self._trans_list = []
if timecnt:
out.trans_list = list(struct.unpack(">%dl" % timecnt,
fileobj.read(timecnt*4)))
else:
out.trans_list = []
# Next come tzh_timecnt one-byte values of type unsigned
# char; each one tells which of the different types of
# ``local time'' types described in the file is associated
# with the same-indexed transition time. These values
# serve as indices into an array of ttinfo structures that
# appears next in the file.
# Next come tzh_timecnt one-byte values of type unsigned
# char; each one tells which of the different types of
# ``local time'' types described in the file is associated
# with the same-indexed transition time. These values
# serve as indices into an array of ttinfo structures that
# appears next in the file.
if timecnt:
self._trans_idx = struct.unpack(">%dB" % timecnt,
fileobj.read(timecnt))
else:
self._trans_idx = []
if timecnt:
out.trans_idx = struct.unpack(">%dB" % timecnt,
fileobj.read(timecnt))
else:
out.trans_idx = []
# Each ttinfo structure is written as a four-byte value
# for tt_gmtoff of type long, in a standard byte
# order, followed by a one-byte value for tt_isdst
# and a one-byte value for tt_abbrind. In each
# structure, tt_gmtoff gives the number of
# seconds to be added to UTC, tt_isdst tells whether
# tm_isdst should be set by localtime(3), and
# tt_abbrind serves as an index into the array of
# time zone abbreviation characters that follow the
# ttinfo structure(s) in the file.
# Each ttinfo structure is written as a four-byte value
# for tt_gmtoff of type long, in a standard byte
# order, followed by a one-byte value for tt_isdst
# and a one-byte value for tt_abbrind. In each
# structure, tt_gmtoff gives the number of
# seconds to be added to UTC, tt_isdst tells whether
# tm_isdst should be set by localtime(3), and
# tt_abbrind serves as an index into the array of
# time zone abbreviation characters that follow the
# ttinfo structure(s) in the file.
ttinfo = []
ttinfo = []
for i in range(typecnt):
ttinfo.append(struct.unpack(">lbb", fileobj.read(6)))
for i in range(typecnt):
ttinfo.append(struct.unpack(">lbb", fileobj.read(6)))
abbr = fileobj.read(charcnt).decode()
abbr = fileobj.read(charcnt).decode()
# Then there are tzh_leapcnt pairs of four-byte
# values, written in standard byte order; the
# first value of each pair gives the time (as
# returned by time(2)) at which a leap second
# occurs; the second gives the total number of
# leap seconds to be applied after the given time.
# The pairs of values are sorted in ascending order
# by time.
# Then there are tzh_leapcnt pairs of four-byte
# values, written in standard byte order; the
# first value of each pair gives the time (as
# returned by time(2)) at which a leap second
# occurs; the second gives the total number of
# leap seconds to be applied after the given time.
# The pairs of values are sorted in ascending order
# by time.
# Not used, for now (but read anyway for correct file position)
if leapcnt:
leap = struct.unpack(">%dl" % (leapcnt*2),
fileobj.read(leapcnt*8))
# Not used, for now (but read anyway for correct file position)
if leapcnt:
leap = struct.unpack(">%dl" % (leapcnt*2),
fileobj.read(leapcnt*8))
# Then there are tzh_ttisstdcnt standard/wall
# indicators, each stored as a one-byte value;
# they tell whether the transition times associated
# with local time types were specified as standard
# time or wall clock time, and are used when
# a time zone file is used in handling POSIX-style
# time zone environment variables.
# Then there are tzh_ttisstdcnt standard/wall
# indicators, each stored as a one-byte value;
# they tell whether the transition times associated
# with local time types were specified as standard
# time or wall clock time, and are used when
# a time zone file is used in handling POSIX-style
# time zone environment variables.
if ttisstdcnt:
isstd = struct.unpack(">%db" % ttisstdcnt,
fileobj.read(ttisstdcnt))
if ttisstdcnt:
isstd = struct.unpack(">%db" % ttisstdcnt,
fileobj.read(ttisstdcnt))
# Finally, there are tzh_ttisgmtcnt UTC/local
# indicators, each stored as a one-byte value;
# they tell whether the transition times associated
# with local time types were specified as UTC or
# local time, and are used when a time zone file
# is used in handling POSIX-style time zone envi-
# ronment variables.
# Finally, there are tzh_ttisgmtcnt UTC/local
# indicators, each stored as a one-byte value;
# they tell whether the transition times associated
# with local time types were specified as UTC or
# local time, and are used when a time zone file
# is used in handling POSIX-style time zone envi-
# ronment variables.
if ttisgmtcnt:
isgmt = struct.unpack(">%db" % ttisgmtcnt,
fileobj.read(ttisgmtcnt))
if ttisgmtcnt:
isgmt = struct.unpack(">%db" % ttisgmtcnt,
fileobj.read(ttisgmtcnt))
# ** Everything has been read **
finally:
if file_opened_here:
fileobj.close()
# Build ttinfo list
self._ttinfo_list = []
out.ttinfo_list = []
for i in range(typecnt):

@@ -369,5 +526,6 @@ gmtoff, isdst, abbrind = ttinfo[i]

# http://python.org/sf/1447945 for some information.
gmtoff = (gmtoff+30)//60*60
gmtoff = 60 * ((gmtoff + 30) // 60)
tti = _ttinfo()
tti.offset = gmtoff
tti.dstoffset = datetime.timedelta(0)
tti.delta = datetime.timedelta(seconds=gmtoff)

@@ -378,9 +536,6 @@ tti.isdst = isdst

tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0)
self._ttinfo_list.append(tti)
out.ttinfo_list.append(tti)
# Replace ttinfo indexes for ttinfo objects.
trans_idx = []
for idx in self._trans_idx:
trans_idx.append(self._ttinfo_list[idx])
self._trans_idx = tuple(trans_idx)
out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx]

@@ -391,27 +546,28 @@ # Set standard, dst, and before ttinfos. before will be

# the first dst, if all of them are dst.
self._ttinfo_std = None
self._ttinfo_dst = None
self._ttinfo_before = None
if self._ttinfo_list:
if not self._trans_list:
self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0]
out.ttinfo_std = None
out.ttinfo_dst = None
out.ttinfo_before = None
if out.ttinfo_list:
if not out.trans_list:
out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0]
else:
for i in range(timecnt-1, -1, -1):
tti = self._trans_idx[i]
if not self._ttinfo_std and not tti.isdst:
self._ttinfo_std = tti
elif not self._ttinfo_dst and tti.isdst:
self._ttinfo_dst = tti
if self._ttinfo_std and self._ttinfo_dst:
tti = out.trans_idx[i]
if not out.ttinfo_std and not tti.isdst:
out.ttinfo_std = tti
elif not out.ttinfo_dst and tti.isdst:
out.ttinfo_dst = tti
if out.ttinfo_std and out.ttinfo_dst:
break
else:
if self._ttinfo_dst and not self._ttinfo_std:
self._ttinfo_std = self._ttinfo_dst
if out.ttinfo_dst and not out.ttinfo_std:
out.ttinfo_std = out.ttinfo_dst
for tti in self._ttinfo_list:
for tti in out.ttinfo_list:
if not tti.isdst:
self._ttinfo_before = tti
out.ttinfo_before = tti
break
else:
self._ttinfo_before = self._ttinfo_list[0]
out.ttinfo_before = out.ttinfo_list[0]

@@ -425,40 +581,110 @@ # Now fix transition times to become relative to wall time.

# about this.
laststdoffset = 0
self._trans_list = list(self._trans_list)
for i in range(len(self._trans_list)):
tti = self._trans_idx[i]
laststdoffset = None
for i, tti in enumerate(out.trans_idx):
if not tti.isdst:
# This is std time.
self._trans_list[i] += tti.offset
laststdoffset = tti.offset
offset = tti.offset
laststdoffset = offset
else:
# This is dst time. Convert to std.
self._trans_list[i] += laststdoffset
self._trans_list = tuple(self._trans_list)
if laststdoffset is not None:
# Store the DST offset as well and update it in the list
tti.dstoffset = tti.offset - laststdoffset
out.trans_idx[i] = tti
def _find_ttinfo(self, dt, laststd=0):
timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400
+ dt.hour * 3600
+ dt.minute * 60
+ dt.second)
idx = 0
for trans in self._trans_list:
if timestamp < trans:
break
idx += 1
else:
offset = laststdoffset or 0
out.trans_list[i] += offset
# In case we missed any DST offsets on the way in for some reason, make
# a second pass over the list, looking for the /next/ DST offset.
laststdoffset = None
for i in reversed(range(len(out.trans_idx))):
tti = out.trans_idx[i]
if tti.isdst:
if not (tti.dstoffset or laststdoffset is None):
tti.dstoffset = tti.offset - laststdoffset
else:
laststdoffset = tti.offset
if not isinstance(tti.dstoffset, datetime.timedelta):
tti.dstoffset = datetime.timedelta(seconds=tti.dstoffset)
out.trans_idx[i] = tti
out.trans_idx = tuple(out.trans_idx)
out.trans_list = tuple(out.trans_list)
return out
def _find_last_transition(self, dt):
# If there's no list, there are no transitions to find
if not self._trans_list:
return None
timestamp = _datetime_to_timestamp(dt)
# Find where the timestamp fits in the transition list - if the
# timestamp is a transition time, it's part of the "after" period.
idx = bisect.bisect_right(self._trans_list, timestamp)
# We want to know when the previous transition was, so subtract off 1
return idx - 1
def _get_ttinfo(self, idx):
# For no list or after the last transition, default to _ttinfo_std
if idx is None or (idx + 1) == len(self._trans_list):
return self._ttinfo_std
if idx == 0:
# If there is a list and the time is before it, return _ttinfo_before
if idx < 0:
return self._ttinfo_before
if laststd:
while idx > 0:
tti = self._trans_idx[idx-1]
if not tti.isdst:
return tti
idx -= 1
else:
return self._ttinfo_std
else:
return self._trans_idx[idx-1]
return self._trans_idx[idx]
def _find_ttinfo(self, dt):
idx = self._resolve_ambiguous_time(dt)
return self._get_ttinfo(idx)
def is_ambiguous(self, dt, idx=None):
"""
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 idx is None:
idx = self._find_last_transition(dt)
# Calculate the difference in offsets from current to previous
timestamp = _datetime_to_timestamp(dt)
tti = self._get_ttinfo(idx)
if idx is None or idx <= 0:
return False
od = self._get_ttinfo(idx - 1).offset - tti.offset
tt = self._trans_list[idx] # Transition time
return timestamp < tt + od
def _resolve_ambiguous_time(self, dt):
idx = self._find_last_transition(dt)
# If we have no transitions, return the index
_fold = self._fold(dt)
if idx is None or idx == 0:
return idx
# Get the current datetime as a timestamp
idx_offset = int(not _fold and self.is_ambiguous(dt, idx))
return idx - idx_offset
def utcoffset(self, dt):

@@ -470,8 +696,14 @@ if dt is None:

return ZERO
return self._find_ttinfo(dt).delta
def dst(self, dt):
if dt is None:
return None
if not self._ttinfo_dst:
return ZERO
tti = self._find_ttinfo(dt)
if not tti.isdst:

@@ -482,15 +714,7 @@ return ZERO

# be constant for every dt.
return tti.delta-self._find_ttinfo(dt, laststd=1).delta
return tti.dstoffset
# An alternative for that would be:
#
# return self._ttinfo_dst.offset-self._ttinfo_std.offset
#
# However, this class stores historical changes in the
# dst offset, so I belive that this wouldn't be the right
# way to implement this.
@tzname_in_python2
def tzname(self, dt):
if not self._ttinfo_std:
if not self._ttinfo_std or dt is None:
return None

@@ -501,3 +725,3 @@ return self._find_ttinfo(dt).abbr

if not isinstance(other, tzfile):
return False
return NotImplemented
return (self._trans_list == other._trans_list and

@@ -507,4 +731,6 @@ self._trans_idx == other._trans_idx and

__hash__ = None
def __ne__(self, other):
return not self.__eq__(other)
return not (self == other)

@@ -515,16 +741,102 @@ def __repr__(self):

def __reduce__(self):
if not os.path.isfile(self._filename):
raise ValueError("Unpickable %s class" % self.__class__.__name__)
return (self.__class__, (self._filename,))
return self.__reduce_ex__(None)
def __reduce_ex__(self, protocol):
return (self.__class__, (None, self._filename), self.__dict__)
class tzrange(datetime.tzinfo):
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
if not relativedelta:
from dateutil import relativedelta
from dateutil import relativedelta
self._std_abbr = stdabbr
self._dst_abbr = dstabbr
try:
stdoffset = _total_seconds(stdoffset)
except (TypeError, AttributeError):
pass
try:
dstoffset = _total_seconds(dstoffset)
except (TypeError, AttributeError):
pass
if stdoffset is not None:

@@ -534,8 +846,10 @@ self._std_offset = datetime.timedelta(seconds=stdoffset)

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)
self._dst_offset = self._std_offset + datetime.timedelta(hours=+1)
else:
self._dst_offset = ZERO
if dstabbr and start is None:

@@ -546,2 +860,3 @@ self._start_delta = relativedelta.relativedelta(

self._start_delta = start
if dstabbr and end is None:

@@ -553,39 +868,33 @@ self._end_delta = relativedelta.relativedelta(

def utcoffset(self, dt):
if dt is None:
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
if self._isdst(dt):
return self._dst_offset
else:
return self._std_offset
base_year = datetime.datetime(year, 1, 1)
def dst(self, dt):
if self._isdst(dt):
return self._dst_offset-self._std_offset
else:
return ZERO
start = base_year + self._start_delta
end = base_year + self._end_delta
@tzname_in_python2
def tzname(self, dt):
if self._isdst(dt):
return self._dst_abbr
else:
return self._std_abbr
return (start, end)
def _isdst(self, dt):
if not self._start_delta:
return False
year = datetime.datetime(dt.year, 1, 1)
start = year+self._start_delta
end = year+self._end_delta
dt = dt.replace(tzinfo=None)
if start < end:
return dt >= start and dt < end
else:
return dt >= start or dt < end
def __eq__(self, other):
if not isinstance(other, tzrange):
return False
return NotImplemented
return (self._std_abbr == other._std_abbr and

@@ -598,17 +907,40 @@ self._dst_abbr == other._dst_abbr and

def __ne__(self, other):
return not self.__eq__(other)
@property
def _dst_base_offset(self):
return self._dst_base_offset_
def __repr__(self):
return "%s(...)" % self.__class__.__name__
__reduce__ = object.__reduce__
class tzstr(tzrange):
"""
``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``.
class tzstr(tzrange):
The :class:`tzrange` object provides the same functionality, but is
specified using :class:`relativedelta.relativedelta` objects. rather than
strings.
def __init__(self, s):
:param s:
A time zone string in ``TZ`` variable format. This can be a
:class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: :class:`unicode`)
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.
.. _`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
if not parser:
from dateutil import parser
from dateutil import parser
self._s = s

@@ -622,3 +954,3 @@

# GMT-3 actually *means* the timezone -3.
if res.stdabbr in ("GMT", "UTC"):
if res.stdabbr in ("GMT", "UTC") and not posix_offset:
res.stdoffset *= -1

@@ -641,3 +973,6 @@

self.hasdst = bool(self._start_delta)
def _delta(self, x, isend=0):
from dateutil import relativedelta
kwargs = {}

@@ -678,4 +1013,4 @@ if x.month is not None:

# of the tzinfo class.
delta = self._dst_offset-self._std_offset
kwargs["seconds"] -= delta.seconds+delta.days*86400
delta = self._dst_offset - self._std_offset
kwargs["seconds"] -= delta.seconds + delta.days * 86400
return relativedelta.relativedelta(**kwargs)

@@ -692,3 +1027,3 @@

self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom
self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom
self.isdst = isdst

@@ -699,4 +1034,6 @@ self.tzname = tzname

class _tzicalvtz(datetime.tzinfo):
class _tzicalvtz(_tzinfo):
def __init__(self, tzid, comps=[]):
super(_tzicalvtz, self).__init__()
self._tzid = tzid

@@ -710,18 +1047,21 @@ self._comps = comps

return self._comps[0]
dt = dt.replace(tzinfo=None)
try:
return self._cachecomp[self._cachedate.index(dt)]
return self._cachecomp[self._cachedate.index((dt, self._fold(dt)))]
except ValueError:
pass
lastcompdt = None
lastcomp = None
lastcompdt = None
for comp in self._comps:
if not comp.isdst:
# Handle the extra hour in DST -> STD
compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True)
else:
compdt = comp.rrule.before(dt, inc=True)
compdt = self._find_compdt(comp, dt)
if compdt and (not lastcompdt or lastcompdt < compdt):
lastcompdt = compdt
lastcomp = comp
if not lastcomp:

@@ -738,9 +1078,20 @@ # RFC says nothing about what to do when a given

lastcomp = comp[0]
self._cachedate.insert(0, dt)
self._cachedate.insert(0, (dt, self._fold(dt)))
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 self._fold(dt):
dt -= comp.tzoffsetdiff
compdt = comp.rrule.before(dt, inc=True)
return compdt
def utcoffset(self, dt):

@@ -770,6 +1121,15 @@ if dt is None:

class tzical(object):
"""
This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure
as set out in `RFC 2445`_ 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 2445`: https://www.ietf.org/rfc/rfc2445.txt
"""
def __init__(self, fileobj):
global rrule
if not rrule:
from dateutil import rrule
from dateutil import rrule

@@ -780,22 +1140,43 @@ if isinstance(fileobj, string_types):

fileobj = open(fileobj, 'r')
elif hasattr(fileobj, "name"):
self._s = fileobj.name
file_opened_here = True
else:
self._s = repr(fileobj)
self._s = getattr(fileobj, 'name', repr(fileobj))
fileobj = _ContextWrapper(fileobj)
self._vtz = {}
self._parse_rfc(fileobj.read())
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:
keys = list(self._vtz.keys())
if len(keys) == 0:
if len(self._vtz) == 0:
raise ValueError("no timezones defined")
elif len(keys) > 1:
elif len(self._vtz) > 1:
raise ValueError("more than one timezone available")
tzid = keys[0]
tzid = next(iter(self._vtz))
return self._vtz.get(tzid)

@@ -813,7 +1194,7 @@

if len(s) == 4:
return (int(s[:2])*3600+int(s[2:])*60)*signal
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
return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal
else:
raise ValueError("invalid offset: "+s)
raise ValueError("invalid offset: " + s)

@@ -943,3 +1324,6 @@ def _parse_rfc(self, s):

TZFILES = ["/etc/localtime", "localtime"]
TZPATHS = ["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/etc/zoneinfo"]
TZPATHS = ["/usr/share/zoneinfo",
"/usr/lib/zoneinfo",
"/usr/share/lib/zoneinfo",
"/etc/zoneinfo"]
else:

@@ -1002,5 +1386,7 @@ TZFILES = []

tz = None
if not tz:
from dateutil.zoneinfo import gettz
tz = gettz(name)
from dateutil.zoneinfo import get_zonefile_instance
tz = get_zonefile_instance().get(name)
if not tz:

@@ -1022,2 +1408,101 @@ for c in name:

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``.
"""
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(tzutc()).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:
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 _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 _total_seconds((dt.replace(tzinfo=None) - EPOCH))
class _ContextWrapper(object):
"""
Class for wrapping contexts so that they are passed through in a
with statement.
"""
def __init__(self, context):
self.context = context
def __enter__(self):
return self.context
def __exit__(*args, **kwargs):
pass
# vim:ts=4:sw=4:et

@@ -15,3 +15,4 @@ # This code was originally contributed by Jeffrey Harris.

from ._common import tzname_in_python2
from ._common import tzname_in_python2, _tzinfo
from ._common import tzrangebase

@@ -45,3 +46,3 @@ __all__ = ["tzwin", "tzwinlocal", "tzres"]

..versionadded:: 2.5.0
.. versionadded:: 2.5.0
"""

@@ -117,9 +118,14 @@ p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char

class tzwinbase(datetime.tzinfo):
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.
return (isinstance(other, tzwinbase) and
(self._stdoffset == other._stdoffset and
self._dstoffset == other._dstoffset and
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

@@ -133,45 +139,12 @@ self._dstdayofweek == other._dstdayofweek and

self._dstminute == other._dstminute and
self._stdname == other._stdname and
self._dstname == other._dstname))
self._std_abbr == other._std_abbr and
self._dst_abbr == other._dst_abbr)
def __ne__(self, other):
return not self.__eq__(other)
def utcoffset(self, dt):
isdst = self._isdst(dt)
if isdst is None:
return None
elif isdst:
return datetime.timedelta(minutes=self._dstoffset)
else:
return datetime.timedelta(minutes=self._stdoffset)
def dst(self, dt):
isdst = self._isdst(dt)
if isdst is None:
return None
elif isdst:
minutes = self._dstoffset - self._stdoffset
return datetime.timedelta(minutes=minutes)
else:
return datetime.timedelta(0)
@tzname_in_python2
def tzname(self, dt):
if self._isdst(dt):
return self._dstname
else:
return self._stdname
@staticmethod
def list():
"""Return a list of all time zones known to the system."""
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
tzkey = winreg.OpenKey(handle, TZKEYNAME)
result = [winreg.EnumKey(tzkey, i)
for i in range(winreg.QueryInfoKey(tzkey)[0])]
tzkey.Close()
handle.Close()
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

@@ -182,21 +155,41 @@

def _isdst(self, dt):
if not self._dstmonth:
# dstmonth == 0 signals the zone has no daylight saving time
return False
elif dt is None:
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(dt.year, self._dstmonth, self._dstdayofweek,
dston = picknthweekday(year, self._dstmonth, self._dstdayofweek,
self._dsthour, self._dstminute,
self._dstweeknumber)
dstoff = picknthweekday(dt.year, self._stdmonth, self._stddayofweek,
dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek,
self._stdhour, self._stdminute,
self._stdweeknumber)
if dston < dstoff:
return dston <= dt.replace(tzinfo=None) < dstoff
else:
return not dstoff <= dt.replace(tzinfo=None) < dston
# 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):

@@ -213,4 +206,4 @@

self._stdname = keydict["Std"]
self._dstname = keydict["Dlt"]
self._std_abbr = keydict["Std"]
self._dst_abbr = keydict["Dlt"]

@@ -221,4 +214,6 @@ self._display = keydict["Display"]

tup = struct.unpack("=3l16h", keydict["TZI"])
self._stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1
self._dstoffset = self._stdoffset-tup[2] # + DaylightBias * -1
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)

@@ -239,2 +234,5 @@ # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs

self._dst_base_offset_ = self._dst_offset - self._std_offset
self.hasdst = self._get_hasdst()
def __repr__(self):

@@ -248,15 +246,13 @@ return "tzwin(%s)" % repr(self._name)

class tzwinlocal(tzwinbase):
def __init__(self):
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey:
keydict = valuestodict(tzlocalkey)
self._stdname = keydict["StandardName"]
self._dstname = keydict["DaylightName"]
self._std_abbr = keydict["StandardName"]
self._dst_abbr = keydict["DaylightName"]
try:
tzkeyname = text_type('{kn}\{sn}').format(kn=TZKEYNAME,
sn=self._stdname)
sn=self._std_abbr)
with winreg.OpenKey(handle, tzkeyname) as tzkey:

@@ -268,5 +264,8 @@ _keydict = valuestodict(tzkey)

self._stdoffset = -keydict["Bias"]-keydict["StandardBias"]
self._dstoffset = self._stdoffset-keydict["DaylightBias"]
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

@@ -292,2 +291,5 @@ # moved to the END of the SYSTEMTIME structure.

self._dst_base_offset_ = self._dst_offset - self._std_offset
self.hasdst = self._get_hasdst()
def __repr__(self):

@@ -298,3 +300,3 @@ return "tzwinlocal()"

# str will return the standard name, not the daylight name.
return "tzwinlocal(%s)" % repr(self._stdname)
return "tzwinlocal(%s)" % repr(self._std_abbr)

@@ -301,0 +303,0 @@ def __reduce__(self):

@@ -16,3 +16,3 @@ # -*- coding: utf-8 -*-

__all__ = ["gettz", "gettz_db_metadata", "rebuild"]
__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata", "rebuild"]

@@ -75,3 +75,19 @@ ZONEFILENAME = "dateutil-zoneinfo.tar.gz"

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

@@ -82,7 +98,66 @@ # a stateful class. So as a workaround for now, without changing the API, we

#
# TODO: deprecate this.
# TODO: Remove after deprecation period.
_CLASS_ZONE_INSTANCE = list()
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(getzoneinfofile_stream())
get_zonefile_instance._cached_instance = zif
return zif
def gettz(name):
"""
This retrieves a time zone from the local zoneinfo tarball that is packaged
with dateutil.
: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:

@@ -98,4 +173,15 @@ _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))

:returns: A dictionary with the database 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:

@@ -102,0 +188,0 @@ _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))

+65
-0

@@ -0,1 +1,66 @@

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

@@ -2,0 +67,0 @@ -------------

Metadata-Version: 1.1
Name: python-dateutil
Version: 2.5.3
Version: 2.6.0
Summary: Extensions to the standard Python datetime module
Home-page: https://dateutil.readthedocs.org
Home-page: https://dateutil.readthedocs.io
Author: Paul Ganssle, Yaron de Leeuw

@@ -26,3 +26,4 @@ Author-email: dateutil@python.org

Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Topic :: Software Development :: Libraries
Requires: six
Metadata-Version: 1.1
Name: python-dateutil
Version: 2.5.3
Version: 2.6.0
Summary: Extensions to the standard Python datetime module
Home-page: https://dateutil.readthedocs.org
Home-page: https://dateutil.readthedocs.io
Author: Paul Ganssle, Yaron de Leeuw

@@ -26,3 +26,4 @@ Author-email: dateutil@python.org

Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Topic :: Software Development :: Libraries
Requires: six

@@ -0,1 +1,4 @@

.gitattributes
.gitignore
.travis.yml
LICENSE

@@ -5,7 +8,15 @@ MANIFEST.in

README.rst
RELEASING
appveyor.yml
codecov.yml
setup.cfg
setup.py
tox.ini
updatezinfo.py
zonefile_metadata.json
ci_tools/pypy_upgrade.sh
ci_tools/retry.bat
ci_tools/retry.sh
dateutil/__init__.py
dateutil/_common.py
dateutil/easter.py

@@ -31,2 +42,14 @@ dateutil/parser.py

dateutil/zoneinfo/rebuild.py
docs/Makefile
docs/conf.py
docs/easter.rst
docs/examples.rst
docs/index.rst
docs/make.bat
docs/parser.rst
docs/relativedelta.rst
docs/rrule.rst
docs/tz.rst
docs/zoneinfo.rst
docs/samples/EST5EDT.ics
python_dateutil.egg-info/PKG-INFO

@@ -33,0 +56,0 @@ python_dateutil.egg-info/SOURCES.txt

@@ -35,3 +35,3 @@ dateutil - powerful extensions to datetime

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

@@ -128,3 +128,3 @@ Code

=========== ============================
2.4.1- `0xCD54FCE3D964BEFB`_
2.4.1- `6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB`_
=========== ============================

@@ -139,3 +139,3 @@

To easily test dateutil against all supported Python versions, you can use
`tox <https://tox.readthedocs.org/en/latest/>`_.
`tox <https://tox.readthedocs.io/en/latest/>`_.

@@ -145,3 +145,3 @@ All github pull requests are automatically tested using travis and appveyor.

.. _0xCD54FCE3D964BEFB:
.. _6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB:
https://pgp.mit.edu/pks/lookup?op=vindex&search=0xCD54FCE3D964BEFB

@@ -5,5 +5,5 @@ [bdist_wheel]

[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
tag_date = 0
tag_build =

@@ -25,3 +25,3 @@ #!/usr/bin/python

author_email="dateutil@python.org",
url="https://dateutil.readthedocs.org",
url="https://dateutil.readthedocs.io",
license="Simplified BSD",

@@ -50,2 +50,3 @@ long_description="""

'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries',

@@ -52,0 +53,0 @@ ],

@@ -7,5 +7,5 @@ {

],
"tzdata_file": "tzdata2016d.tar.gz",
"tzdata_file_sha512": "f1beb1793c4c7d18f2dadaf4a928b1476f66b400bda0c87b06155c0dd1c4b4a26bb2f37dc17a3676a2bbe9c1e71a5d8b27a171c797a86464b0bc0d13abfb2f99",
"tzversion": "2016d",
"tzdata_file": "tzdata2016i.tar.gz",
"tzdata_file_sha512": "801059f43c91798cf69fb2ae77c1ffab8d06987325081511d573febde19ae423e7432c2b65c7c256077bbdb1b359e010302955786e18f2697bb263c4e0f1cc91",
"tzversion": "2016i",
"zonegroups": [

@@ -12,0 +12,0 @@ "africa",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet