pandas · Chapter 18 of 22

Dates and times

By the end of this chapter you can turn text into real dates with pd.to_datetime (with format=, dayfirst= and errors="coerce"), take dates apart with the .dt accessor, read dates straight from a CSV file, put dates in the index and select by a day, a month or a slice of days, subtract dates to get durations, and build a full calendar with pd.date_range. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Time
  • 4 tasks
  • pandas
  • In the all labs plan

The first 2 chapters of pandas are free. This one comes with the all labs plan.

Why you need this

Every one of Kargha's questions has a date in it: what sold in Diwali week, how many days the courier takes, which weekday is busiest, which months beat their targets. So far every date has been text. Text dates sort as text, cannot be subtracted, and know nothing about weekdays. Here is a column of Gopal's handwritten delivery slips, typed the way he writes them, day first:

import pandas as pd

slips = pd.Series(["06/09/2026", "13/09/2026", "20/09/2026", "05/10/2026"])
print(slips.sort_values().tolist())
['05/10/2026', '06/09/2026', '13/09/2026', '20/09/2026']

5 October comes first, because "0" sorts before "1" and "2", character by character. The website's dates are written year first, so they happen to sort right as text, but ask how long a delivery took and text gives up:

site = pd.read_csv("/workspace/data/orders_site.csv")
site["delivered_on"] - site["placed_at"]
TypeError: operation 'sub' not supported for dtype 'str' with dtype 'str'

Until now the lab took months from text with .str.slice(0, 7). That works for months and nothing else: no weekdays, no hours, no "days between". pandas has a real type for moments in time, and this chapter is how to get your dates into it and what it gives you.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    dates.py: each channel's dates, read properly

    Write three functions in dates.py. Each is given a Series of text and returns a Series of dates (datetime64) with the same labels, in the same order:

    site_times(text) reads the website's placed_at, written like "2025-10-01 11:55:03".

    market_dates(text) reads the marketplace's Order Date, day first, written like "05-03-2026" (5 March 2026, not 3 May).

    store_times(text) reads the store's time, written like "2025-10-01 10:00".

    A value that is not a date written that way ("not placed", "closed", "31-02-2026", a missing value) becomes a missing date (NaT) and must not stop the function. The Check tries each real column and a few small values of its own for each function, with labels that are not 0, 1, 2.

  2. Task 2

    delivery.py: days to deliver, by city

    Write delivery_days(lines) in delivery.py. lines is the website's lines with their cities cleaned; placed_at ("2025-10-01 11:55:03") and delivered_on ("2025-10-08", or a missing value when the line was never delivered) are still text. A line's days to deliver is the date of delivered_on minus the date it was placed, in whole calendar days: a line placed at 23:50 on 1 January and delivered on 3 January took 2 days, not 1.

    Return a Series labelled by city, in alphabetical order, each value the median of that city's days to deliver, a decimal number. Lines with no delivered_on do not count. The Check tries the whole website file and 5 small lines (one placed at 23:50, one never delivered).

  3. Task 3

    festival.py: the orders of a festival week

    Write between_days(lines, first, last) in festival.py. lines is the website's lines as read_csv reads orders_site.csv, with placed_at as text; first and last are days written as text, like "2025-10-14". Return the lines placed on any day from first to last, both days whole (all of the last day, up to 23:59:59).

    The result is a DataFrame labelled by placed_at as dates (datetime64), in time order (lines placed at the same moment may come in any order among themselves). Its columns are the lines' other columns, in their order; placed_at is no longer a column.

    The Check tries Diwali week (2025-10-14 to 2025-10-20), 1 and 2 March 2026, and 14 and 15 June 2026, when the website was down: no rows, but the same columns and a date index.

  4. Task 4 · interview question

    Interview: market_order.py, sorted but not by date

    Harpreet's in_date_order(market) should give the marketplace's orders oldest first. market is the Orders sheet as read_excel reads it (two banner lines skipped); its Order Date is text, day first ("02-10-2025" is 2 October 2025). Her version put 01-11-2025 (1 November) before 02-10-2025 (2 October). Fix it so it returns the same rows and columns, with Order Date as dates (datetime64), oldest first. Each row keeps its own label (the one it has in market); rows of the same day may come in any order. The Check tries the whole sheet and 5 small orders.

    Devika will ask: why did sorting the Order Date put 01-11-2025 before 02-10-2025?

What you will learn

  • pd.to_datetime: text to dates, with format=, dayfirst= and errors="coerce".
  • datetime64: how pandas 3 stores a moment (microseconds), and NaT for a missing one.
  • The .dt accessor: year, month, day, hour, day_name, day_of_week, date, normalize, to_period.
  • parse_dates= in read_csv.
  • A date index: select a day, a month (a partial string) or a slice of days.
  • Durations: a Timedelta from subtracting dates, .dt.days, pd.Timedelta for comparisons.
  • pd.date_range: every day of a year, to find the days that are missing.

More in Time

Build "Dates and times" yourself

Kargha, a Varanasi handloom brand, sells through a website, a marketplace and a store. You make one true picture of its sales. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of pandas are free. This one comes with the all labs plan.