Working with Date and Time Columns
Many datasets include timestamps — like sales records, sensor readings, or user activity logs.
Pandas simplifies working with these by letting you convert strings into datetime objects, extract specific components, and filter by time periods.
Converting Strings to Datetime
To work with dates, first convert them from string format using:
Convert column to datetime
df["Date"] = pd.to_datetime(df["Date"])
This converts the column into true datetime objects, allowing you to easily sort, filter, and extract specific components.
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 technique is especially useful for analyzing trends over time or comparing specific time periods.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.