Work with Dates in pandas
Turn text into real dates, then get the weekday, filter by month or count days between dates.
- pd.to_datetime
- The .dt accessor: day_name, month, year
- Date arithmetic with Timedelta
- 1
pd.to_datetime(...)A real date - 2
.dt.day_name()Monday - 3
.dt.month8
Text → datetime → useful parts
The problem
Dates usually arrive as text, such as "2026-08-10". Text cannot tell you the weekday, sort by month or measure the days between two events. Converting to real dates unlocks all of that.
Think of it like this
Converting text to dates is like turning handwritten notes into calendar entries. Once an entry is on the calendar, the calendar knows its weekday, its month and how far it is from any other entry.
"2026-08-10"📝 A date written as textpd.to_datetime(...)📅 Put it on the calendar.dt.day_name()🗓️ Ask the calendar for the weekdayMonday✅ The answer for every row at oncepd.to_datetime converts text or numbers into datetime values, and the .dt accessor gives date parts such as the weekday, month or year for a whole column.
Key points
pd.to_datetime(events["date"])turns the text dates into datetime values.- Assigning the result back to
events["date"]replaces the text column. .dt.day_name()returns the weekday for every row: Monday and Wednesday.- The new
daycolumn is added to the same table.
When should you use it?
- Reports by day, week or month.
- Calculating durations and deadlines.
- Filtering a time range, such as the last 30 days.
When not to use it
- Dates in an unusual or ambiguous format, such as 03/04/2026: pass
format=ordayfirst=True. - A single date in plain Python code: the
datetimemodule is enough.
Example code
import pandas as pd
events = pd.DataFrame({"date": ["2026-08-10", "2026-08-12"]})
events["date"] = pd.to_datetime(events["date"])
events["day"] = events["date"].dt.day_name()
print(events)
Result of running the code
date day
0 2026-08-10 Monday
1 2026-08-12 Wednesday
Code explanation
To_datetime converts text to datetime values. The dt accessor exposes vectorized date components such as day names.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Add rows, columns, and missing values.
- Combine filtering, sorting, and groupby into a small report.
- Load a real file, inspect dtypes, and handle invalid data.
Common mistakes
Using .dt on text
The .dt accessor only works on datetime columns.
events["date"].dt.day_name() # AttributeError on text
pd.to_datetime(events["date"]).dt.day_name()
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges