Partial types¶
This section describes the partial types: the types that hold part of
a datetime. They are Date, Time, YearMonth,
MonthDay, and IsoWeekDate.
Overview¶
Type |
Represents |
Example |
|---|---|---|
A calendar date (year, month, day) |
|
|
A time of day (hour, minute, second…) |
|
|
A year and month without a day |
|
|
A month and day without a year |
|
|
An ISO 8601 week date (year, week, weekday) |
|
Date¶
Date represents a calendar date. It supports arithmetic with
ItemizedDateDelta and calculating the difference between two dates:
>>> d = Date(2023, 1, 31)
>>> d.add(months=1) # End-of-month pinning
Date("2023-02-28")
>>> d.since(Date(2022, 10, 15), in_units=["months", "days"])
ItemizedDateDelta("P3m16d")
You can combine a Date with a Time to get a PlainDateTime,
from either side:
>>> Date(2023, 6, 15).at(Time(9, 0))
PlainDateTime("2023-06-15 09:00:00")
>>> Time(9, 0).on(Date(2023, 6, 15))
PlainDateTime("2023-06-15 09:00:00")
A Date also finds dates near it:
next_day()andprev_day()step one day.nth_weekday()finds the n-th occurrence of a weekday from the date, exclusive of the date itself; negativensearches backward.nth_weekday_of_month()finds the n-th occurrence of a weekday in the date’s month; negativencounts from the end.start_of()andend_of()give the first and last day of the date’s year or month, or of its week with"week_mon"or"week_sun"; see Rounding and boundaries.
Time¶
Time represents a time of day, independent of any date or time zone.
Sub-second precision is supported down to nanoseconds.
>>> Time(14, 30, nanosecond=500_000_000)
Time("14:30:00.5")
round() rounds to a unit from an hour down to a nanosecond,
wrapping past midnight when it rounds up; see Rounding and boundaries.
YearMonth and MonthDay¶
YearMonth and MonthDay are useful for recurring events or
partial date specifications (e.g. a birthday or an annual deadline):
>>> YearMonth(2024, 3).on_day(22)
Date("2024-03-22")
>>> YearMonth(2024, 3).add(months=10)
YearMonth("2025-01")
>>> MonthDay(2, 29).in_year(2024)
Date("2024-02-29")
>>> MonthDay(2, 29).is_leap_day()
True
YearMonth.add() and subtract() take years and
months as keywords. An ItemizedDateDelta is a mapping, so it
unpacks into them; a delta carrying weeks or days raises TypeError,
since a year-month has no day to shift:
>>> delta = ItemizedDateDelta(years=1, months=2)
>>> YearMonth(2024, 3).add(**delta)
YearMonth("2025-05")
IsoWeekDate¶
IsoWeekDate is a date in the ISO 8601 week date system.
Date.iso_week_date() and IsoWeekDate.date() are a round trip:
>>> Date(2024, 12, 30).iso_week_date()
IsoWeekDate("2025-W01-1")
>>> IsoWeekDate(2025, 1, Weekday.MONDAY).date()
Date("2024-12-30")