We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Dates and Times

If you were paying attention in the last lesson, you likely noticed that we totally skipped over dates and times – a huge mistake, given how common they are in real data.

Dates are deceptively tricky. They look simple. They are not simple. Python's built-in datetime module is the standard library tool for working with them.

In real datasets, you'll find:

  • Different date formats
  • Missing time zones
  • Weird offsets
  • Inconsistent timestamps
  • Business logic like "last 30 days" or "next business week"

... and it's up to you to figure out how to handle it.

Parsing Timestamps

You'll often receive a timestamp as a string:

timestamp = "2026-05-28 14:30:00"

Which you'll then convert to a datetime object using datetime.strptime():

from datetime import datetime

timestamp = datetime.strptime("2026-05-28 14:30:00", "%Y-%m-%d %H:%M:%S")
print(timestamp)
# 2026-05-28 14:30:00

The timestamp here is an actual datetime object, not just a string. You can do math with it, compare it to other dates, etc.

That format string, "%Y-%m-%d %H:%M:%S", tells Python how to parse the text as a date and time:

  • %Y = 4-digit year
  • %m = month
  • %d = day
  • %H = hour in 24-hour time
  • %M = minute
  • %S = second

Mixture of Formats

Different sources will often hand you different stringified date and time formats:

iso_date = datetime.strptime("2024-01-15", "%Y-%m-%d")
us_date = datetime.strptime("01/15/2024", "%m/%d/%Y")
eu_date = datetime.strptime("15/01/2024", "%d/%m/%Y")

If the format string doesn't match the text exactly, parsing fails, and that's why dates are such a common cleaning problem.

The standard library makes working with dates and times bearable, but they're still annoying. For more complex pipelines, you'll eventually lean on tools like Pandas, dateutil, or zoneinfo... more on that later.

Assignment

SnackStack's smart appliances send event timestamps as strings... guh.

Complete the parse_reading_timestamp function. It accepts a timestamp string and returns a datetime object.

Parse the timestamp with datetime.strptime() using the format string "%Y-%m-%d %H:%M:%S".

The incoming timestamp string looks like "2022-02-22 02:22:22".