ZetCode

Python dateutil

last modified November 19, 2026 Python 3.15

In this article we work with the dateutil library, which extends the standard datetime module. It adds month and year arithmetic with relativedelta, a forgiving date parser, recurrence rules as used in calendar applications, and the date of Easter.

The examples use dateutil 4.0, which requires Python 3.11 or later. For time zones, it relies on the same IANA database as the standard zoneinfo module, which we use in this article. The examples were run with the local time zone set to Europe/Bratislava.

$ pip install python-dateutil

Adding months

A timedelta has no months, because months have different lengths. A relativedelta has them.

first_relativedelta.py
from datetime import date, timedelta

from dateutil.relativedelta import relativedelta

start = date(2026, 1, 31)

print(start + timedelta(days=30))
print(start + relativedelta(months=1))
print(start + relativedelta(months=2))
print(start + relativedelta(years=1, months=1, days=3))
print(start - relativedelta(months=3))

print(relativedelta(months=1) * 3)
print([str(start + relativedelta(months=n)) for n in range(4)])

Thirty days after January 31 is March 2, while one month after it is February 28: relativedelta clamps the day to the end of the month. Each addition starts from the original date, so two months later is March 31 again. Plural arguments such as months and days are relative and can be combined, subtracted, and multiplied.

$ python first_relativedelta.py
2026-03-02
2026-02-28
2026-03-31
2027-03-03
2025-10-31
relativedelta(months=+3)
['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30']

Absolute fields

Singular arguments such as day and month do not add anything; they set the field to a value.

absolute_fields.py
from datetime import datetime

from dateutil.relativedelta import relativedelta

now = datetime(2026, 11, 19, 14, 35, 12)

print(now + relativedelta(day=1))
print(now + relativedelta(day=31))
print(now + relativedelta(month=2, day=31))
print(now + relativedelta(months=1, day=1))
print(now + relativedelta(hour=0, minute=0, second=0))
print(now + relativedelta(years=1, month=1, day=1, hour=0, minute=0, second=0))

print(relativedelta(months=1) + relativedelta(day=31))

The day=1 argument gives the first day of the month, and day=31 the last one, because the day is clamped to the length of the month. Absolute fields are applied before relative ones, so months=1, day=1 is the first day of the next month. Setting the time fields to zero truncates a datetime to midnight, and the last example gives midnight of next New Year's Day.

$ python absolute_fields.py
2026-11-01 14:35:12
2026-11-30 14:35:12
2026-02-28 14:35:12
2026-12-01 14:35:12
2026-11-19 00:00:00
2027-01-01 00:00:00
relativedelta(months=+1, day=31)

Weekdays

The weekday argument moves a date to a given day of the week. The constants MO to SU take an optional count and direction.

weekdays.py
from datetime import date

from dateutil.relativedelta import FR, MO, TH, relativedelta

today = date(2026, 11, 19)

print(today + relativedelta(weekday=FR))
print(today + relativedelta(weekday=TH))
print(today + relativedelta(days=1, weekday=TH))
print(today + relativedelta(weekday=MO(-1)))
print(today + relativedelta(weekday=FR(+2)))

print(today + relativedelta(day=31, weekday=FR(-1)))
print(today + relativedelta(day=1, weekday=TH(+4)))
print(today + relativedelta(years=1, month=5, day=31, weekday=MO(-1)))

mondays = [date(2026, m, 1) + relativedelta(weekday=MO(+1)) for m in range(1, 13)]
print([d.day for d in mondays])

November 19, 2026 is a Thursday. weekday=FR moves to the next Friday, and weekday=TH stays on the same day, because the current day counts. To get the following Thursday, we add a day first. MO(-1) is the previous Monday and FR(+2) the second Friday. Combined with absolute days, the argument expresses rules such as the last Friday of the month, the fourth Thursday of November, or the last Monday of May next year. The list holds the day of the first Monday of every month.

$ python weekdays.py
2026-11-20
2026-11-19
2026-11-26
2026-11-16
2026-11-27
2026-11-27
2026-11-26
2027-05-31
[5, 2, 2, 6, 4, 1, 6, 3, 7, 5, 2, 7]

Differences in years and months

Called with two dates, relativedelta returns the difference in years, months, and days.

difference.py
from datetime import date, datetime

from dateutil.relativedelta import relativedelta

born = date(1990, 5, 3)
today = date(2026, 11, 19)

age = relativedelta(today, born)
print(age)
print(age.years, age.months, age.days)
print((today - born).days)

start = datetime(2026, 1, 31, 9, 0)
end = datetime(2026, 3, 1, 17, 30)
print(relativedelta(end, start))
print(relativedelta(start, end))

print(relativedelta(hours=50, minutes=90).normalized())
print(relativedelta(months=14) == relativedelta(years=1, months=2))

The difference between a birth date and today is the age: 36 years, 6 months, and 16 days. A timedelta gives only the number of days. Reversing the arguments gives a negative result. The normalized method converts large values into larger units, here 50 hours and 90 minutes into 2 days, 3 hours, and 30 minutes. Months are not converted into years, but two deltas with equal total months compare equal.

$ python difference.py
relativedelta(years=+36, months=+6, days=+16)
36 6 16
13349
relativedelta(months=+1, days=+1, hours=+8, minutes=+30)
relativedelta(months=-1, days=-1, hours=-8, minutes=-30)
relativedelta(days=+2, hours=+3, minutes=+30)
True

Parsing dates

The parser.parse function recognizes many date formats without a format string, unlike strptime, which the parse dates article covers.

first_parse.py
from dateutil import parser

texts = [
    "2026-11-19",
    "19 November 2026",
    "Nov 19, 2026 2:30 PM",
    "Thursday, 19 Nov 2026 14:30:00",
    "2026/11/19 14:30",
    "20261119T143000",
    "14:30",
]

for text in texts:
    print(f"{text:32} {parser.parse(text)}")

The parser handles ISO dates, month names, AM and PM, weekday names, and compact forms. Missing parts come from the current date, so the string 14:30 gives today at 14:30; the output depends on the day the program runs.

$ python first_parse.py
2026-11-19                       2026-11-19 00:00:00
19 November 2026                 2026-11-19 00:00:00
Nov 19, 2026 2:30 PM             2026-11-19 14:30:00
Thursday, 19 Nov 2026 14:30:00   2026-11-19 14:30:00
2026/11/19 14:30                 2026-11-19 14:30:00
20261119T143000                  2026-11-19 14:30:00
14:30                            2026-11-19 14:30:00

Ambiguous dates

A date such as 03/04/05 can be read in several ways. The parser assumes month first unless we tell it otherwise.

ambiguous.py
from dateutil import parser

text = "03/04/05"

print(parser.parse(text))
print(parser.parse(text, dayfirst=True))
print(parser.parse(text, yearfirst=True))
print(parser.parse(text, yearfirst=True, dayfirst=True))

print(parser.parse("13/04/2026"))
print(parser.parse("04/13/2026", dayfirst=True))

print(parser.parse("2026-04-03", dayfirst=True))
print(parser.parse("3.4.2026", dayfirst=True))

By default, 03/04/05 is March 4, 2005. The dayfirst and yearfirst options change the order. When a number cannot be a month, such as 13, the parser swaps the fields on its own, whatever the options say. Beware of dayfirst=True with ISO dates: it turns 2026-04-03 into March 4. Use the option only for input that is known to be in day-first order, such as 3.4.2026.

$ python ambiguous.py
2005-03-04 00:00:00
2005-04-03 00:00:00
2003-04-05 00:00:00
2003-05-04 00:00:00
2026-04-13 00:00:00
2026-04-13 00:00:00
2026-03-04 00:00:00
2026-04-03 00:00:00

Defaults and fuzzy parsing

The default argument fills in missing parts, and fuzzy skips words that are not part of a date.

fuzzy.py
from datetime import datetime

from dateutil import parser

base = datetime(2026, 11, 1)

print(parser.parse("Friday", default=base))
print(parser.parse("Dec 24", default=base))
print(parser.parse("10:15", default=base))

text = "The meeting moved to 24 Nov 2026 at 10am"
print(parser.parse(text, fuzzy=True))
print(parser.parse(text, fuzzy_with_tokens=True))

texts = ["The meeting moved to 24 Nov 2026 at 10am in room 4",
         "next week", "2026-02-30"]
for text in texts:
    try:
        print(parser.parse(text, fuzzy=True))
    except parser.ParserError as e:
        print("ParserError:", e)

With a default of November 1, 2026, a weekday name gives the next such day, a month and day keep the default year, and a time keeps the default date. Fuzzy parsing finds the date in a sentence, and fuzzy_with_tokens also returns the skipped parts. It has limits: the extra number in "room 4" breaks the parse, and relative phrases such as "next week" are not supported. Invalid dates raise ParserError, a subclass of ValueError.

$ python fuzzy.py
2026-11-06 00:00:00
2026-12-24 00:00:00
2026-11-01 10:15:00
2026-11-24 10:00:00
(datetime.datetime(2026, 11, 24, 10, 0), ('The meeting moved to ', ' ', 'at '))
ParserError: Unknown string format: The meeting moved to 24 Nov 2026 at 10am in room 4
ParserError: String does not contain a date: next week
ParserError: day 30 must be in range 1..28 for month 2 in year 2026: 2026-02-30

Time zones in parsed strings

The parser returns an aware datetime when the string contains an offset or a zone name it knows.

parse_zones.py
from zoneinfo import ZoneInfo

from dateutil import parser

print(parser.parse("2026-11-19 14:30 +01:00"))
print(parser.parse("2026-11-19 14:30Z"))
print(repr(parser.parse("Thu, 19 Nov 2026 14:30:00 GMT").tzinfo))

print(parser.parse("19 Nov 2026 14:30 EST"))

zones = {"CET": ZoneInfo("Europe/Bratislava"),
         "EST": ZoneInfo("America/New_York"),
         "PST": -8 * 3600}
for text in ("19 Nov 2026 14:30 CET", "19 Nov 2026 14:30 EST",
             "19 Nov 2026 14:30 PST"):
    dt = parser.parse(text, tzinfos=zones)
    print(dt, dt.tzinfo)

print(parser.isoparse("2026-11-19T14:30:00+01:00"))
print(parser.isoparse("2026-W47-4"))
print(parser.isoparse("20261119T1430"))

Numeric offsets, Z, UTC, and GMT are understood. Other abbreviations are ambiguous; EST is unknown, so the parser issues an UnknownTimezoneWarning and returns a naive datetime. The tzinfos mapping assigns a time zone or an offset in seconds to each abbreviation. The stricter isoparse function accepts only ISO 8601 strings, including week dates such as 2026-W47-4.

$ python parse_zones.py
2026-11-19 14:30:00+01:00
2026-11-19 14:30:00+00:00
tzutc()
/home/user/python/.venv/lib/python3.15/site-packages/dateutil/parser/_parser.py:1201: UnknownTimezoneWarning: tzname EST identified but not understood.  Pass `tzinfos` argument in order to correctly return a timezone-aware datetime.  In a future version, this will raise an exception.
  warnings.warn("tzname {tzname} identified but not understood.  "
2026-11-19 14:30:00
2026-11-19 14:30:00+01:00 Europe/Bratislava
2026-11-19 14:30:00-05:00 America/New_York
2026-11-19 14:30:00-08:00 tzoffset('PST', -28800)
2026-11-19 14:30:00+01:00
2026-11-19 00:00:00
2026-11-19 14:30:00

Recurring dates

The rrule class generates recurring dates following the iCalendar standard (RFC 5545), which calendar applications use for repeating events.

first_rrule.py
from datetime import datetime

from dateutil.rrule import DAILY, MONTHLY, WEEKLY, rrule

start = datetime(2026, 11, 19, 9, 0)

for dt in rrule(DAILY, dtstart=start, count=3):
    print(dt)

weekly = rrule(WEEKLY, dtstart=start, until=datetime(2026, 12, 31))
print([dt.strftime("%b %d") for dt in weekly])

every_other = rrule(DAILY, interval=2, dtstart=start, count=5)
print([dt.day for dt in every_other])

monthly = rrule(MONTHLY, dtstart=datetime(2026, 1, 31), count=6)
print([dt.strftime("%b %d") for dt in monthly])

A rule has a frequency, a start, and an end given by count or until; interval skips occurrences. Iterating over a rule yields datetimes. Note the monthly rule that starts on January 31: following the standard, it skips the months that have no 31st, unlike relativedelta, which clamps the day.

$ python first_rrule.py
2026-11-19 09:00:00
2026-11-20 09:00:00
2026-11-21 09:00:00
['Nov 19', 'Nov 26', 'Dec 03', 'Dec 10', 'Dec 17', 'Dec 24']
[19, 21, 23, 25, 27]
['Jan 31', 'Mar 31', 'May 31', 'Jul 31', 'Aug 31', 'Oct 31']

Rules with by-parts

The by arguments restrict or expand the occurrences: by month, by day of the month, by weekday, and by position within the period.

by_rules.py
from datetime import datetime

from dateutil.rrule import FR, MO, MONTHLY, TH, TU, WEEKLY, YEARLY, rrule

start = datetime(2026, 1, 1)


def show(label, rule):
    print(f"{label:16}", " ".join(dt.strftime("%Y-%m-%d") for dt in rule))


show("month ends", rrule(MONTHLY, bymonthday=-1, dtstart=start, count=5))
show("last Fridays", rrule(MONTHLY, byweekday=FR(-1), dtstart=start, count=5))
show("Tue and Thu", rrule(WEEKLY, byweekday=(TU, TH), dtstart=start, count=5))
show("Thanksgiving", rrule(YEARLY, bymonth=11, byweekday=TH(4),
                           dtstart=start, count=5))
show("last workday", rrule(MONTHLY, byweekday=range(5), bysetpos=-1,
                           dtstart=start, count=5))
show("Friday 13th", rrule(MONTHLY, bymonthday=13, byweekday=FR,
                          dtstart=start, count=5))
show("first Monday", rrule(MONTHLY, byweekday=MO(1), dtstart=start,
                           until=datetime(2026, 5, 31)))

A negative bymonthday counts from the end of the month, and FR(-1) in a monthly rule means the last Friday. Several weekdays give several occurrences per week. With bysetpos=-1, the rule takes all weekdays of each month and keeps only the last one, which is the last working day. Combining bymonthday=13 with byweekday=FR finds the days that satisfy both.

$ python by_rules.py
month ends       2026-01-31 2026-02-28 2026-03-31 2026-04-30 2026-05-31
last Fridays     2026-01-30 2026-02-27 2026-03-27 2026-04-24 2026-05-29
Tue and Thu      2026-01-01 2026-01-06 2026-01-08 2026-01-13 2026-01-15
Thanksgiving     2026-11-26 2027-11-25 2028-11-23 2029-11-22 2030-11-28
last workday     2026-01-30 2026-02-27 2026-03-31 2026-04-30 2026-05-29
Friday 13th      2026-02-13 2026-03-13 2026-11-13 2027-08-13 2028-10-13
first Monday     2026-01-05 2026-02-02 2026-03-02 2026-04-06 2026-05-04

Querying a rule

A rule can be indexed, counted, and searched without generating all of its dates by hand.

queries.py
from datetime import datetime

from dateutil.rrule import WE, WEEKLY, rrule

standup = rrule(WEEKLY, byweekday=WE, byhour=10, byminute=0, bysecond=0,
                dtstart=datetime(2026, 1, 1), until=datetime(2026, 12, 31))

print(standup.count(), standup[0], standup[-1])

now = datetime(2026, 11, 19, 14, 0)
print(standup.after(now))
print(standup.before(now))
print(standup.after(datetime(2026, 11, 25, 10, 0), inc=True))

december = standup.between(datetime(2026, 12, 1), datetime(2027, 1, 1))
print([dt.day for dt in december])

print(datetime(2026, 12, 2, 10, 0) in standup)
print(datetime(2026, 12, 3, 10, 0) in standup)

The stand-up meeting is held every Wednesday at 10:00 in 2026, 52 times. The after and before methods find the nearest occurrences; inc=True includes an occurrence at the given time itself. The between method returns the occurrences in an interval, and the in operator tests whether a datetime is one of them.

$ python queries.py
52 2026-01-07 10:00:00 2026-12-30 10:00:00
2026-11-25 10:00:00
2026-11-18 10:00:00
2026-11-25 10:00:00
[2, 9, 16, 23, 30]
True
False

Rule sets

Real schedules have exceptions. An rruleset combines rules with excluded rules and single added or removed dates.

ruleset.py
from datetime import datetime

from dateutil.rrule import FR, MO, WEEKLY, rrule, rruleset

start = datetime(2026, 12, 1, 9, 0)
end = datetime(2027, 1, 15)

lessons = rruleset()
lessons.rrule(rrule(WEEKLY, byweekday=(MO, FR), dtstart=start, until=end))
lessons.exrule(rrule(WEEKLY, byweekday=(MO, FR), dtstart=datetime(2026, 12, 21, 9),
                     until=datetime(2027, 1, 3)))
lessons.exdate(datetime(2026, 12, 7, 9, 0))
lessons.rdate(datetime(2026, 12, 9, 9, 0))
lessons.rdate(datetime(2027, 1, 7, 9, 0))

for dt in lessons:
    print(dt.strftime("%a %d %b %H:%M"))

The lessons are on Mondays and Fridays. The exrule method removes the Christmas break, exdate removes a single cancelled lesson, and rdate adds two extra lessons on a Wednesday and a Thursday. Iteration returns all dates in order.

$ python ruleset.py
Fri 04 Dec 09:00
Wed 09 Dec 09:00
Fri 11 Dec 09:00
Mon 14 Dec 09:00
Fri 18 Dec 09:00
Mon 04 Jan 09:00
Thu 07 Jan 09:00
Fri 08 Jan 09:00
Mon 11 Jan 09:00

iCalendar rules

Calendar files store recurrence rules as text. The rrulestr function parses them.

rrule_text.py
from datetime import datetime

from dateutil.rrule import rrulestr

rule = rrulestr("FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=1;COUNT=4",
                dtstart=datetime(2026, 11, 1, 8, 0))
print([str(dt) for dt in rule])
print(rule)

text = """DTSTART:20261123T180000
RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=MO;UNTIL=20270131T235959
EXDATE:20261221T180000"""

meetings = rrulestr(text, forceset=True)
print([dt.strftime("%b %d") for dt in meetings])

The first rule gives the first working day of each month. Converting a rule to a string gives the iCalendar form back. The second text contains a start, a rule, and an excluded date, as found in an .ics file; with forceset=True, the result is an rruleset, so the meeting on December 21 is left out.

$ python rrule_text.py
['2026-11-02 08:00:00', '2026-12-01 08:00:00', '2027-01-01 08:00:00', '2027-02-01 08:00:00']
DTSTART:20261101T080000
RRULE:FREQ=MONTHLY;COUNT=4;BYSETPOS=1;BYDAY=MO,TU,WE,TH,FR
['Nov 23', 'Dec 07', 'Jan 04', 'Jan 18']

Easter

Easter is a movable feast computed from the lunar calendar. The easter function computes it, and several holidays follow from it.

easter_dates.py
from datetime import timedelta

from dateutil.easter import EASTER_ORTHODOX, easter

for year in range(2026, 2031):
    western = easter(year)
    orthodox = easter(year, EASTER_ORTHODOX)
    print(year, western, orthodox, (orthodox - western).days)

sunday = easter(2027)
print("Good Friday:  ", sunday - timedelta(days=2))
print("Easter Monday:", sunday + timedelta(days=1))
print("Ascension:    ", sunday + timedelta(days=39))
print("Pentecost:    ", sunday + timedelta(days=49))

Western and Orthodox Easter fall on the same day in some years, such as 2028, and up to five weeks apart in others. Good Friday, Easter Monday, Ascension, and Pentecost are fixed offsets from Easter Sunday, so they can feed a holiday set like the one in the date ranges article.

$ python easter_dates.py
2026 2026-04-05 2026-04-12 7
2027 2027-03-28 2027-05-02 35
2028 2028-04-16 2028-04-16 0
2029 2029-04-01 2029-04-08 7
2030 2030-04-21 2030-04-28 7
Good Friday:   2027-03-26
Easter Monday: 2027-03-29
Ascension:     2027-05-06
Pentecost:     2027-05-16

Source

dateutil documentation

RFC 5545 – Recurrence Rule

In this article we have used the dateutil library to add months and compute differences with relativedelta, parse free-form dates, generate recurring dates with rrule, and compute Easter. See also Python datetime, Python date ranges, Python parse dates, and Python arrow.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.