Working with Dates and Strings
Explore how to convert text timestamps into datetime objects using pandas, calculate time durations, extract calendar features, and summarize ticket data in weekly bins. This lesson helps you prepare and clean date and string data for reliable analysis and reporting within Python and SQL environments.
Ticket timestamps arrive as text, but the question “Are incident tickets getting resolved more slowly this quarter than last?” requires durations and calendar-based summaries. Starting from a small tickets DataFrame, the complete pipeline converts created_at and resolved_at into dates and times, calculates resolution_hours, then reports ticket-level results. The input expects timestamp strings that pandas can parse and no missing resolution timestamps in the rows used for the calculation.
Datetime parsing converts strings such as 2025-04-07 09:15 into pandas datetime64 values. Once both columns have that dtype, subtracting resolved_at - created_at produces a duration rather than an invalid string operation. The .dt accessor then exposes parts of each duration, including total seconds.
Lines 26–27:
pd.to_datetimeconverts the timestamp-lookingobjectcolumns intodatetime64[ns], which is what enables.dtaccessors and datetime arithmetic.Lines 29–31: Subtracting the two datetime columns produces timedeltas;
.dt.total_seconds() / 3600turns each duration into a numeric hour value (2.5, 4.0, 1.25 for the sample rows) that’s easy to summarize.Lines 33–37: The output is limited to the two datetime dtypes (to verify the conversion) and the ticket-level table including the computed
resolution_hours.
This code prints datetime dtypes for created_at and resolved_at, then returns a numeric resolution_hours value for every resolved ticket. Dividing total seconds by 3600 makes the result easy to summarize, so a ticket resolved after two and a half hours ...