The .dt Accessor
Pull parts out of a datetime column with .dt — year, month, day, day_name, quarter, dayofweek, is_month_end — and format dates as text with strftime.
Watch the lesson
1 video on CodeWithMunnaX
Once a column is a real datetime, you can ask it questions: Which season (year) was this match? Which month? Was it a weekend? Which quarter? In Munna's IPL analysis this is how the year and month columns are created — ipl3['year'] = ipl3['date'].dt.year — and then used to count matches per season. The tool is the .dt accessor.
Definition
The
.dtaccessor gives a datetime Series access to date-and-time properties and methods, applied to every element at once: properties like.dt.yearor.dt.day_name()return a new Series with that component for each row, and missing dates (NaT) give missing results.
- Datetime Series —
.dtonly works ondatetime64(ortimedelta64/ period) columns. On a text column you getAttributeError: Can only use .dt accessor with datetimelike values— convert withpd.to_datetimefirst. - Properties vs methods —
year,month,quarterare properties (no brackets);day_name(),month_name(),strftime()are methods (with brackets). - Every element at once — like
.str, it is vectorized.
Syntax
python
s.dt.year s.dt.month s.dt.day s.dt.hour s.dt.minute
s.dt.quarter s.dt.dayofweek s.dt.dayofyear s.dt.date
s.dt.day_name() s.dt.month_name()
s.dt.is_month_end s.dt.is_month_start s.dt.is_leap_year
s.dt.isocalendar().week
s.dt.strftime(format)| Attribute / method | Returns | Example for 2024-03-22 19:30 (a Friday) |
|---|---|---|
year, month, day | integers | 2024, 3, 22 |
hour, minute, second | integers | 19, 30, 0 |
quarter | 1–4 | 1 |
dayofweek (alias weekday) | Monday = 0 … Sunday = 6 | 4 |
dayofyear | 1–366 | 82 |
day_name() / month_name() | text | Friday / March |
is_month_end / is_month_start | bool | False / False |
is_leap_year | bool | True |
date / time | Python date / time objects | 2024-03-22 / 19:30:00 |
isocalendar() | DataFrame: year, week, day | week 12 |
strftime(fmt) | formatted text | "22 Mar 2024" |
Example — pull out the parts
python
ipl = pd.DataFrame({
"match": ["CSK vs RCB", "MI vs GT", "RR vs LSG", "KKR vs SRH"],
"start": pd.to_datetime(["2024-03-22 20:00", "2024-03-24 19:30",
"2024-03-24 15:30", "2024-05-26 19:30"]),
})
ipl["year"] = ipl["start"].dt.year
ipl["month"] = ipl["start"].dt.month
ipl["day"] = ipl["start"].dt.day
ipl["hour"] = ipl["start"].dt.hour
print(ipl)
print(ipl.dtypes)text
match start year month day hour
0 CSK vs RCB 2024-03-22 20:00:00 2024 3 22 20
1 MI vs GT 2024-03-24 19:30:00 2024 3 24 19
2 RR vs LSG 2024-03-24 15:30:00 2024 3 24 15
3 KKR vs SRH 2024-05-26 19:30:00 2024 5 26 19
match str
start datetime64[us]
year int32
month int32
day int32
hour int32
dtype: objectHow it works: each property returns one number per row. They come back as compact int32 integers. Because the result is a Series, you can store it as a new column, group by it, or filter on it.
Example — names, quarter, weekday
python
print(pd.DataFrame({
"start": ipl["start"].dt.date,
"day_name": ipl["start"].dt.day_name(),
"month_name": ipl["start"].dt.month_name(),
"quarter": ipl["start"].dt.quarter,
"dayofweek": ipl["start"].dt.dayofweek,
"weekend": ipl["start"].dt.dayofweek >= 5,
}))text
start day_name month_name quarter dayofweek weekend
0 2024-03-22 Friday March 1 4 False
1 2024-03-24 Sunday March 1 6 True
2 2024-03-24 Sunday March 1 6 True
3 2024-05-26 Sunday May 2 6 TrueHow it works: dayofweek counts from Monday = 0, so Saturday = 5 and Sunday = 6, and >= 5 marks weekend matches. day_name() and month_name() are methods — note the brackets. The 2024 final (26 May) was on a Sunday.
Example — month ends and starts
python
d = pd.Series(pd.to_datetime(["2024-03-31", "2024-04-01", "2024-04-15", "2024-02-29"]))
print(pd.DataFrame({"date": d,
"month_end": d.dt.is_month_end,
"month_start": d.dt.is_month_start,
"leap_year": d.dt.is_leap_year,
"week": d.dt.isocalendar().week}))text
date month_end month_start leap_year week
0 2024-03-31 True False True 13
1 2024-04-01 False True True 14
2 2024-04-15 False False True 16
3 2024-02-29 True False True 9Example — format dates as text with strftime
python
print(ipl["start"].dt.strftime("%d %b %Y").tolist())
print(ipl["start"].dt.strftime("%A, %d %B").tolist())
print(ipl["start"].dt.strftime("%I:%M %p").tolist())text
['22 Mar 2024', '24 Mar 2024', '24 Mar 2024', '26 May 2024']
['Friday, 22 March', 'Sunday, 24 March', 'Sunday, 24 March', 'Sunday, 26 May']
['08:00 PM', '07:30 PM', '03:30 PM', '07:30 PM']strftime uses the same % codes as format= in pd.to_datetime (%d day, %b short month, %Y year, %A weekday, %I 12-hour, %p AM/PM). The result is text — use it for display and reports, not for further date maths.
Example — use the parts: matches per month and weekday filter
python
season = pd.DataFrame({"date": pd.to_datetime([
"2024-03-22", "2024-03-23", "2024-03-30", "2024-04-06", "2024-04-07",
"2024-04-14", "2024-04-20", "2024-05-04", "2024-05-19", "2024-05-26"])})
print(season["date"].dt.month_name().value_counts(sort=False))
weekend = season[season["date"].dt.dayofweek >= 5]
print(len(weekend), "weekend matches out of", len(season))text
date
March 3
April 4
May 3
Name: count, dtype: int64
9 weekend matches out of 10Example — NaT stays missing
python
d = pd.Series(pd.to_datetime(["2024-03-22", None]))
print(d.dt.year)
print(d.dt.day_name())text
0 2024.0
1 NaN
dtype: float64
0 Friday
1 NaN
dtype: strA missing date gives a missing part. Note the year becomes float64 here (NaN forces float), or use .astype("Int64").
Common mistakes
- ❌
df["date"].dt.yearon a text column →AttributeError. ✅df["date"] = pd.to_datetime(df["date"])first. - ❌
s.dt.day_namewithout brackets → returns a method object, not names. ✅s.dt.day_name(). - ❌ Thinking
dayofweekstarts at Sunday or at 1. ✅ Monday = 0, Sunday = 6. - ❌ Using
strftimeoutput for sorting/arithmetic. ✅ Keep the datetime column; usestrftimeonly for display. - ❌
s.dt.week(removed). ✅s.dt.isocalendar().week.
Interview tip
Q: How do you count matches per season from a date column?
A: df["date"].dt.year.value_counts().sort_index() — or create df["year"] = df["date"].dt.year and groupby("year").
Key points to remember
- .dt works only on datetime columns — convert text with pd.to_datetime first.
- Properties year, month, day, hour, quarter, dayofweek, dayofyear need no brackets.
- day_name(), month_name() and strftime() are methods — use brackets.
- dayofweek counts Monday = 0 … Sunday = 6, so dayofweek >= 5 means weekend.
- is_month_end / is_month_start / is_leap_year return True/False per row.
- strftime('%d %b %Y') formats dates as text for display; isocalendar().week gives the week number.
- NaT gives a missing result, so integer parts may become float.
Try it yourself
Year, month, day and weekday
Pretty dates with strftime
Practice: matches per month and per weekday
Revision Flashcards
Tap a card to flip it and see the answer.
