TECHNOLOGIESTieInn Technologies

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= or dayfirst=True, or it may become 4 March.
  • .dt only works on datetime columns; an object column 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.days for a number.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Dates in pandas

  1. Question 1easy

    How do you get the year of each value in the datetime column orders["order_date"]?

  2. Dates in pandas

  3. Question 2medium

    A file has dates like "03-04-2024", meaning 3 April. How do you parse them correctly?

  4. Dates in pandas

  5. Question 3medium

    What does this print?

    gap = (orders["shipped_date"] - orders["order_date"]).dt.days
    print(int(gap.max()))
  6. Dates in pandas

  7. 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()))
  8. Dates in pandas

  9. Question 5easy

    You loaded a CSV and df["order_date"].dt.year raises "Can only use .dt accessor with datetimelike values". What's wrong?

11 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.