Search⌘ K
AI Features

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.

Python
import pandas as pd
def main() -> None:
tickets = pd.DataFrame(
{
"ticket_id": [101, 102, 103],
"created_at": [
"2025-04-07 09:15",
"2025-04-07 10:00",
"2025-04-07 13:30",
],
"resolved_at": [
"2025-04-07 11:45",
"2025-04-07 14:00",
"2025-04-07 14:45",
],
"issue_summary": [
" LOGIN failure ",
"Payment declined",
"Password reset",
],
}
)
tickets["created_at"] = pd.to_datetime(tickets["created_at"])
tickets["resolved_at"] = pd.to_datetime(tickets["resolved_at"])
tickets["resolution_hours"] = (
(tickets["resolved_at"] - tickets["created_at"]).dt.total_seconds() / 3600
)
print("Datetime dtypes:")
print(tickets[["created_at", "resolved_at"]].dtypes)
print()
print("Ticket resolution results:")
print(tickets[["ticket_id", "created_at", "resolved_at", "resolution_hours"]])
if __name__ == "__main__":
main()
  • Lines 26–27: pd.to_datetime converts the timestamp-looking object columns into datetime64[ns], which is what enables .dt accessors and datetime arithmetic.

  • Lines 29–31: Subtracting the two datetime columns produces timedeltas; .dt.total_seconds() / 3600 turns 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 ...