Working with Date and Time Columns
Many datasets include timestamps such as sales logs, sensor data, or user activity.
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, first convert them from string format using:
Convert column to datetime
df["Date"] = pd.to_datetime(df["Date"])
This allows pandas to treat dates as real datetime objects so you can 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 is useful for analyzing data over time or comparing different periods.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.