Working with Date and Time Columns
Many datasets include timestamps — sales logs, sensor data, user activity, and more. Pandas makes it easy to convert strings to datetime objects, extract date parts, and filter by time ranges.
Converting Strings to Datetime
To work with dates, you need to convert them from string format using:
Convert column to datetime
df["Date"] = pd.to_datetime(df["Date"])
This lets pandas treat dates as real datetime objects so you can sort, filter, and extract parts of a date.
Useful Date Components
Once converted, you can extract parts like:
Access date components
df["Year"] = df["Date"].dt.year
df["Weekday"] = df["Date"].dt.day_name()
You can now analyze trends by year, month, or day of the week.
Time-Based Filtering
You can also filter by date ranges:
Filter after a certain date
df[df["Date"] > "2023-01-01"]
This is useful for analyzing data over time or comparing periods.
What’s Next?
Next, you’ll take everything you’ve learned and test it in the Final Quiz for this chapter.