Dates in pandas
Python · 16 questions
Short notes
Key idea
Turn date text into real datetimes first; then pandas can pull out parts, resample by period and do date maths.
Syntax
df["order_date"] = pd.to_datetime(df["order_date"])
pd.to_datetime(s, format="%d-%m-%Y", errors="coerce")
df["order_date"].dt.year, .dt.month, .dt.day_name()
df["order_date"].dt.to_period("M")
df["days"] = (df["ship_date"] - df["order_date"]).dt.days
df.set_index("order_date").resample("MS")["amount"].sum()
df[df["order_date"] >= "2024-03-01"]
Example
Monthly revenue:
monthly = (df.assign(month=df["order_date"].dt.to_period("M"))
.groupby("month")["amount"].sum())
print(monthly)
to_period("M") keeps the year, so March 2023 and March 2024 stay apart.
Traps
- Indian dates are day first. "03-04-2024" is 3 April; pass
format=ordayfirst=True, or it may become 4 March. .dtonly works on datetime columns; anobjectcolumn means conversion hasn't happened.errors="coerce"turns bad dates into NaT; count them, don't ignore them.- Subtracting dates gives a Timedelta; use
.dt.daysfor a number.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
How do you get the year of each value in the datetime column
orders["order_date"]? - Question 2medium
A file has dates like "03-04-2024", meaning 3 April. How do you parse them correctly?
- Question 3medium
What does this print?
gap = (orders["shipped_date"] - orders["order_date"]).dt.days print(int(gap.max()))
- Question 4hard
Orders in 2024 run from January to November, and October 2024 has no orders. What does this print?
o24 = orders[orders["order_date"].dt.year == 2024] print(len(o24.set_index("order_date").resample("MS").size())) - Question 5easy
You loaded a CSV and
df["order_date"].dt.yearraises "Can only use .dt accessor with datetimelike values". What's wrong?
Dates in pandas
Dates in pandas
Dates in pandas
Dates in pandas
Dates in pandas
11 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.