Sub topic 12
Periods and PeriodIndex for calendar spans
This chapter assumes you can already parse text with pd.to_datetime, use a DatetimeIndex, and call resample and groupby on a time series. It builds on the earlier chapters about Timestamp and Timedelta. Here you meet the third core type, Period, which stands for a whole span of calendar time instead of one instant.
Why a span type exists
A Timestamp names one moment, such as 2024-03-01 00:00:00. A monthly total, a quarterly report, or a fiscal year does not belong to one moment. It belongs to the whole stretch of time that the label covers.
If you label March data with 2024-03-01, readers can mistake that label for midnight on the first day. A Period removes that ambiguity. The label 2024-03 means March, with its start and end defined by the frequency.
| Type | Represents | Typical question it answers |
|---|---|---|
| `Timestamp` | One instant | When did this event happen? |
| `Timedelta` | A length of time | How long between two events? |
| `Period` | A calendar span with a frequency | Which month, quarter, or year does this belong to? |
Creating and inspecting a Period
A Period is made from a string or date plus a frequency alias. The alias sets the size of the span.
import pandas as pd
p = pd.Period("2024-03", freq="M")
print(p)
print(p.start_time)
print(p.end_time)
print(p + 1)
print(p.asfreq("D", how="start"))
print(p.ordinal)The output is:
2024-03
2024-03-01 00:00:00
2024-03-31 23:59:59.999999999
2024-04
2024-03-01
650Four details matter here.
start_timeandend_timereturnTimestampvalues. The end is the last nanosecond of the span, not midnight of the next day.- Adding an integer moves by that many spans of the period's own frequency.
p + 1is April, whatever the length of March. asfreqre-expresses the period at another frequency. Withhow="start"it picks the first day. Withhow="end"it picks the last.ordinalis the integer pandas stores internally. It counts spans since 1970. March 2024 is month 650 because54 * 12 + 2 = 650.
Because periods are stored as integers, they sort and compare quickly and without ambiguity.
Frequencies that Periods support
Periods use the same alias idea as date_range, but the aliases name spans. Common ones are D (day), W (week), M (month), Q (quarter), and Y (year).
Quarters and years can be anchored to a different end month. This is how you handle fiscal calendars.
fq = pd.Period("2024Q1", freq="Q-JUN")
print(fq.start_time, fq.end_time)
print(fq.qyear)This prints 2023-07-01 00:00:00 2023-09-30 23:59:59.999999999, then 2024. With Q-JUN the fiscal year ends in June, so fiscal Q1 of 2024 covers July through September 2023. The qyear attribute gives the fiscal year, and year would give the calendar year of the start.
PeriodIndex and period_range
A PeriodIndex is an index made of periods, just as a DatetimeIndex is made of timestamps. You build one with pd.period_range, which mirrors pd.date_range.
pr = pd.period_range("2024-01", periods=4, freq="M")
print(pr)
a = pd.Period("2024-06", freq="M")
b = pd.Period("2024-03", freq="M")
print((a - b).n)The index prints as PeriodIndex(['2024-01', '2024-02', '2024-03', '2024-04'], dtype='period[M]'). Subtracting two periods of the same frequency gives a multiple of the frequency unit. The .n attribute reads off the count, which is 3 here.
A column of periods has dtype period[M]. Partial-string selection works on a PeriodIndex much as it does on a DatetimeIndex. For example, s.loc["2024-02"] selects every row in February.
Converting between Timestamp and Period
Two methods move data between the two worlds.
to_period(freq)turns timestamps into the periods that contain them.to_timestamp(how="start")turns periods back into timestamps, at the start or end of each span.
days = pd.date_range("2024-01-30", periods=5, freq="D")
sales = pd.Series([5, 7, 3, 8, 2], index=days)
by_month = sales.groupby(sales.index.to_period("M")).sum()
print(by_month)
print(by_month.to_timestamp())
print(by_month.to_timestamp(how="end"))The grouped result has two rows. 2024-01 holds 12, from January 30 and 31. 2024-02 holds 13, from February 1 to 3. The two to_timestamp calls label those rows with 2024-01-01 and 2024-02-01, then with the last nanosecond of each month.
For a DataFrame column rather than an index, use the .dt accessor: df["when"].dt.to_period("M").
Period grouping versus resample
sales.resample("ME").sum() and sales.groupby(sales.index.to_period("M")).sum() give the same totals. They differ in three ways.
- Index type.
resamplereturns aDatetimeIndexlabeled with month-end timestamps. Thegroupbyversion returns aPeriodIndex. - Empty spans.
resamplefills gaps with empty bins automatically.groupbyonly shows periods that appear in the data. To get zeros orNaNfor missing months, callreindexwith a fullperiod_range. - Meaning of the label. A period label like
2024-02states the span. A timestamp like2024-02-29can be read as a single day.
full = pd.period_range("2024-01", "2024-04", freq="M")
print(by_month.reindex(full, fill_value=0))This adds 2024-03 and 2024-04 with value 0. Use resample when you want to keep working with timestamps, for example with rolling windows. Use periods when the result is a report keyed by calendar span, or when you want to join against other data that is keyed that way.
Changing the frequency of periods
asfreq on a Period or PeriodIndex maps each span to the span of another frequency that contains it, or to its start or end.
m = pd.Period("2024-03", freq="M")
print(m.asfreq("Q"))
print(m.asfreq("Y"))
print(m.asfreq("D", how="end"))This prints 2024Q1, 2024, and 2024-03-31. Moving to a coarser frequency (month to quarter) is unambiguous, because each month sits inside exactly one quarter. Moving to a finer frequency (month to day) needs how, because a month contains many days. The default is "end".
Common errors and how to debug them
Mixing frequencies
Arithmetic and comparison between periods of different frequency raise an error. A month and a day are different kinds of span.
x = pd.Period("2024-06", freq="M")
y = pd.Period("2024-03-05", freq="D")
try:
x - y
except ValueError as err:
print(type(err).__name__)This prints IncompatibleFrequency, a subclass of ValueError. Fix it by converting both sides to the same frequency with asfreq first.
Treating end_time as the next midnight
end_time is 23:59:59.999999999 on the last day. If you filter with ts < p.end_time, you miss almost nothing, but ts == p.end_time is almost never true. To test whether a timestamp falls in a period, convert it instead of comparing bounds:
t = pd.Timestamp("2024-03-15 10:00")
print(t.to_period("M") == pd.Period("2024-03", freq="M"))
print(p.start_time <= t <= p.end_time)Both lines print True. The first states the intent more clearly.
Time zones disappear
A Period has no time zone. Calling to_period on tz-aware data drops the zone and emits a UserWarning. The period is then computed from the local wall-clock time, which may not be the day boundary you wanted. Convert to the zone whose calendar you care about with tz_convert before calling to_period. Do not strip the zone beforehand.
Expecting Period columns to behave like datetimes
Many datetime-only features do not apply. You cannot subtract a Period from a Timestamp, and plotting libraries may need to_timestamp() first. If a downstream tool rejects a period[M] column, convert it with .dt.to_timestamp() at the boundary and keep periods inside your analysis code.
Ambiguous labels after a round trip
to_timestamp() defaults to the start of each span. If you convert back and forth, the original data is not recovered unless you keep the same frequency. A series that was daily, converted to monthly periods and back, is monthly data labeled at month start.
Choosing the right type
- Use
Timestampfor events with an exact time, or when time zones matter. - Use
Timedeltafor durations between two timestamps. - Use
Periodwhen the unit of analysis is a calendar span: month, quarter, fiscal year, or ISO-style week. - Use a
PeriodIndexwhen you want sorted, gap-aware calendar labels, or fiscal calendars through anchored aliases likeQ-JUN.
Exercise
A DataFrame df has a datetime64 column when and a numeric column amount. Write code that computes total amount per calendar quarter and returns a Series indexed by Period values, with quarters that have no rows shown as 0. Assume the data spans 2023Q4 to 2024Q2.
Show answer
Convert the column to quarterly periods, group, then reindex against a full range: q = df["when"].dt.toperiod("Q") totals = df.groupby(q)["amount"].sum() full = pd.periodrange("2023Q4", "2024Q2", freq="Q") totals = totals.reindex(full, fill_value=0) The groupby only contains quarters present in the data. The reindex adds the missing ones with 0.
Exercise
A company's fiscal year ends in March (Q-MAR). Which calendar months does pd.Period("2025Q1", freq="Q-MAR") cover, and which attribute gives the fiscal year of a period?
Show answer
Fiscal 2025 ends in March 2025, so fiscal Q1 is April through June 2024. You can confirm it with start_time and end_time, which give 2024-04-01 and 2024-06-30 (at 23:59:59.999999999). The qyear attribute returns the fiscal year, 2025.