Dates and Ordered Data
Extract Date Parts
Pull year and month from a sequence of date strings into separate lists. By
hand, parse each string with datetime.date.fromisoformat and read .year
and .month. With pandas, .dt.year and .dt.month extract all values
from a datetime64 Series without looping.
By hand
With pandas
After pd.to_datetime, use s.dt.year.tolist() and s.dt.month.tolist() to
extract all year and month values in a single vectorized step per component.
naive.py
import datetime
date_strs = ['2024-01-15', '2024-03-22', '2024-07-04', '2024-11-11']
years = []
months = []
for s in date_strs:
d = datetime.date.fromisoformat(s)
years.append(d.year)
months.append(d.month)
print('RESULT:', (years, months))
library.py
import pandas as pd
from dalib.display import set_display
set_display()
date_strs = ['2024-01-15', '2024-03-22', '2024-07-04', '2024-11-11']
df = pd.DataFrame({'date': date_strs})
s = pd.to_datetime(df['date'])
years = s.dt.year.tolist()
months = s.dt.month.tolist()
print('index:', s.index.tolist())
print('years:', years)
print('months:', months)
print('RESULT:', (years, months))
index: [0, 1, 2, 3]
years: [2024, 2024, 2024, 2024]
months: [1, 3, 7, 11]
RESULT: ([2024, 2024, 2024, 2024], [1, 3, 7, 11])
Implementation notes
- The
.dtaccessor is available on anydatetime64Series. Common components:.dt.year,.dt.month,.dt.day,.dt.hour,.dt.dayofweek(Monday=0),.dt.day_name(),.dt.quarter. tolist()converts int64 component Series to Python ints — matching stdlib.year/.monthwhich are also plain ints, so the RESULT strings compare equal without any conversion.- Cross-reference:
parse-date-column(this chapter) to produce thedatetime64Series this lesson starts from.