Sub topic 8
Frequency aliases and date offsets
Earlier chapters used strings such as "D", "W", and "B" as freq arguments without explaining them. This chapter explains what those strings mean, how pandas turns them into offset objects, and where the rules for month ends, weeks, and business days catch people out.
It assumes you can build a DatetimeIndex, call pd.date_range, and use resample at a basic level. The examples target pandas 2.2 or later.
What a frequency string is
A frequency alias is a short string that names a regular step in time. When you pass freq="ME" to date_range, resample, or shift, pandas converts the string into an offset object with pandas.tseries.frequencies.to_offset. The offset object does the real work.
There are two kinds of offsets:
- Fixed-length offsets always span the same amount of elapsed time. Examples are
Hour,Minute, andSecond. Pandas calls these Tick offsets. - Calendar-aware offsets depend on the calendar, so the step length varies. Examples are
MonthEnd,BusinessDay, andQuarterBegin. A month step is 28 to 31 days, and a business-day step from Friday lands on Monday.
Common aliases
| Alias | Offset | Meaning |
|---|---|---|
| `D` | `Day` | Calendar day |
| `B` | `BusinessDay` | Monday to Friday |
| `h` | `Hour` | Hour |
| `min` | `Minute` | Minute |
| `s` | `Second` | Second |
| `W` | `Week` | Weekly, anchored on Sunday by default |
| `MS` | `MonthBegin` | First day of each month |
| `ME` | `MonthEnd` | Last day of each month |
| `QS` / `QE` | `QuarterBegin` / `QuarterEnd` | Quarter start or end |
| `YS` / `YE` | `YearBegin` / `YearEnd` | Year start or end |
| `BME` / `BMS` | `BusinessMonthEnd` / `BusinessMonthBegin` | Last or first business day of the month |
The S and E suffixes mean start and end. Older code and tutorials use M, Q, A, Y, H, T, and S for these. Pandas 2.2 deprecated the older spellings, and later versions reject them. If you see FutureWarning: 'M' is deprecated or a ValueError about an invalid frequency, switch to the names in the table. The old "S" for seconds is now lowercase "s", which is easy to confuse with the S suffix in MS.
Multiples, combinations, and anchors
Put an integer in front of an alias to take larger steps. Put several units together to build a compound step. Add a suffix after a hyphen to choose the anchor.
import pandas as pd
print(pd.date_range("2024-01-31", periods=4, freq="ME"))
print(pd.date_range("2024-01-15", periods=3, freq="MS"))
print(pd.date_range("2024-03-01 09:00", periods=3, freq="2h30min"))
print(pd.date_range("2024-01-01", periods=3, freq="W-MON"))Each call behaves differently:
"ME"from January 31 gives January 31, February 29, March 31, and April 30. The step is "the last day of the month", not "31 days"."MS"starting on January 15 does not start on January 15. Anchored offsets snap the first value forward to the next date that sits on the offset, so the result starts on February 1."2h30min"is a fixed 150-minute step, so the values are 09:00, 11:30, and 14:00."W-MON"gives weeks anchored on Monday. Plain"W"is the same as"W-SUN".
Quarter and year offsets take a month suffix. "QE-DEC" is the default quarter end for a calendar year. "QE-JUN" gives quarters that end in March, June, September, and December from a fiscal year that ends in June. "YE-MAR" gives year ends on March 31.
You can inspect the resulting object, and the index remembers it:
import pandas as pd
from pandas.tseries.frequencies import to_offset
offset = to_offset("2h30min")
print(offset)
idx = pd.date_range("2024-01-31", periods=4, freq="ME")
print(idx.freq)
print(idx.freqstr)Doing arithmetic with offset objects
You can import offset classes from pandas.tseries.offsets (also available as pd.offsets) and add them directly to a Timestamp.
import pandas as pd
from pandas.tseries.offsets import BDay, MonthEnd
friday = pd.Timestamp("2024-03-08")
print(friday + BDay(1))
print(friday - BDay(5))
month_end = pd.Timestamp("2024-03-31")
print(month_end + MonthEnd(1))
print(month_end + MonthEnd(0))
print(pd.Timestamp("2024-03-10") + MonthEnd(0))The output is:
2024-03-11, because one business day after Friday is Monday.2024-03-01, five business days before March 8.2024-04-30, because a date already on the offset moves a full step.2024-03-31, becauseMonthEnd(0)means "roll forward only if not already on the offset".2024-03-31, the same rule applied to a mid-month date.
MonthEnd(0) is useful when you want to snap dates to the end of their month without moving dates that are already there.
Offsets also provide three helper methods:
import pandas as pd
from pandas.tseries.offsets import MonthEnd
me = MonthEnd()
d = pd.Timestamp("2024-03-10")
print(me.is_on_offset(d))
print(me.rollforward(d))
print(me.rollback(d))This prints False, 2024-03-31, and 2024-02-29. rollforward and rollback leave dates that are already on the offset unchanged.
`DateOffset` and month arithmetic
pd.DateOffset follows calendar rules like a person adding months on a wall calendar. It takes keyword arguments such as months, years, days, and weekday.
import pandas as pd
jan31 = pd.Timestamp("2024-01-31")
print(jan31 + pd.DateOffset(months=1))
print(jan31 + pd.DateOffset(months=1, days=2))
print(jan31 + pd.Timedelta(days=30))Adding one month to January 31 gives February 29. When the target month is too short, pandas clips to its last day. The second line gives March 2. The third line adds exactly 30 elapsed days and gives March 1. A Timedelta is a fixed duration and a DateOffset is a calendar step, so choose by what the question means. "Thirty days after" is a Timedelta. "The same day next month" is a DateOffset.
Business days and custom calendars
B ignores weekends but knows nothing about holidays. For a calendar with holidays or a different working week, build a CustomBusinessDay.
import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay
cbd = CustomBusinessDay(holidays=["2024-03-11"])
print(pd.date_range("2024-03-08", periods=3, freq=cbd))
six_day = CustomBusinessDay(weekmask="Mon Tue Wed Thu Fri Sat")
print(pd.date_range("2024-03-08", periods=3, freq=six_day))The first range is March 8, 12, and 13. March 11 is a Monday holiday, so it is skipped. The second range is March 8, 9, and 11, because Saturday counts as a working day and Sunday does not. You can pass the offset object anywhere a frequency string is accepted.
Aliases in `resample`, and the label difference
resample takes the same aliases. The choice between start and end anchors changes the labels on the result, not the grouping.
import pandas as pd
s = pd.Series(1, index=pd.date_range("2024-01-01", periods=60, freq="D"))
print(s.resample("ME").sum())
print(s.resample("MS").sum())Both calls give 31 for January and 29 for February. With "ME" the labels are January 31 and February 29. With "MS" they are January 1 and February 1. Pick the one that matches how the result will be read or joined to other data.
Inferring a frequency
An index only has a freq attribute when pandas knows the step. A DatetimeIndex read from data usually has freq=None, even if the spacing is regular. pd.infer_freq examines the spacing and returns an alias, or None if the spacing is irregular.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
print(pd.infer_freq(idx))
print(pd.infer_freq(idx[[0, 1, 3]]))The first call prints D. The second prints None because the gaps are one day and then two days. infer_freq needs at least three timestamps.
Common errors
- Using
"M","H","T", or"A". These are the old spellings. UseME,h,min, andYE. - Expecting
"W"to mean "every 7 days from my start date"."W"anchors on Sunday. Use"7D"for a fixed seven-day step, or"W-MON"to anchor on Monday. - Expecting
"MS"or"ME"to keep the start date's day. Anchored offsets snap to the calendar anchor, as the January 15 example showed. - Assuming
+ MonthEnd(1)always moves one calendar month. From a mid-month date it moves to that month's end. From a month end it moves to the next month's end. - Mixing up
BandD. A"D"range contains weekends. A"B"range does not. - Treating a missing
freqas an error. Afreq=Noneindex works for selection andresample. It only matters for operations that need a fixed step, such asshiftwith nofreqargument on some index types.
Choosing an alias
- Decide whether the step is fixed in elapsed time or tied to the calendar. Use
h,min,s, or aTimedeltafor the first, andME,MS,B, orW-XXXfor the second. - For calendar steps, decide whether labels should mark the start or end of each span (
SorE). - If holidays or a nonstandard work week matter, build a
CustomBusinessDayrather than filtering the result afterward. - Check
idx.freqstronce the index exists.
Exercise
What dates does pd.date_range("2024-02-10", periods=3, freq="ME") produce, and what does pd.Timestamp("2024-02-29") + pd.offsets.MonthEnd(0) return?
Show answer
The range gives 2024-02-29, 2024-03-31, and 2024-04-30. The first value is snapped forward from February 10 to the February month end, and 2024 is a leap year. The Timestamp expression returns 2024-02-29, because the date is already on the offset and MonthEnd(0) does not move dates that are on the offset.
Exercise
A daily series called s covers January 1 to March 31. You want one row per month labeled with the first day of the month, with the mean of each month. Write the line, and explain why s.resample("W") would not suit a "per month" report.
Show answer
s.resample("MS").mean(). The MS alias groups by calendar month and labels each group with its first day. "W" groups into weeks anchored on Sunday, and weeks do not line up with month boundaries, so a week that crosses a month end would be assigned to one label only.
Exercise
You need the five business days starting on 2024-12-24, skipping December 25 and December 26. How do you build the range?
Show answer
cbd = pd.offsets.CustomBusinessDay(holidays=["2024-12-25", "2024-12-26"]) followed by pd.date_range("2024-12-24", periods=5, freq=cbd). The result is December 24, 27, 30, 31, and January 1. December 28 and 29 are a weekend, and the two holidays are skipped.