~/learn/Pandas · Time series

Datetime columns and indexes

Parse dates once, then slice time like a pro.

8 min readlesson 9 of 13to_datetimedtindex

why this matters

Dates read from a CSV arrive as plain text, so sorting and filtering go wrong until you convert them properly.

Dates arriving as text should be converted once with pd.to_datetime. After that the .dt accessor exposes every calendar part as a column.

python · editable
loading editor…

Try it: Add an is_weekend column using dt.dayofweek.

Setting the date as the index unlocks string-based slicing: pass a partial date and pandas selects the whole period.

python · editable
loading editor…

Note

If dates still show up as object dtype, the parse silently failed on some rows. Pass format= or errors='coerce' and inspect the NaTs.

Common gotcha

Sorting text dates like '3/1/2024' sorts alphabetically, not chronologically. Always convert with pd.to_datetime first.

Pro tip

Once a datetime column is the index, you can slice with df.loc['2024-03'] to get a whole month.

key takeaways

  • pd.to_datetime parses text into real dates.
  • The .dt accessor exposes year, month, weekday.
  • A datetime index unlocks time-based slicing.

check your understanding

How do you get the month number from a datetime column?

free practice

Build confidence with a question you can solve without Pro.