Parsing Dates

A date read from a file is text until you say otherwise.

to_datetime turns text into dates

Until it does, sorting is alphabetical and "greater than" means later in the alphabet rather than later in time.

import pandas as pd

s = pd.Series(["2024-03-01", "2024-01-15"])
print(s.sort_values().tolist())
print(pd.to_datetime(s).sort_values().dt.strftime("%Y-%m-%d").tolist())

Parsing on the way in

parse_dates on read_csv does it at load time, which is one fewer step to forget.

import pandas as pd

df = pd.read_csv("visits.csv", parse_dates=["day"])
print(str(df["day"].dtype))

Exercise

Try It Yourself

Write earliest(dates) that takes a Series of date strings and returns the earliest as a string in YYYY-MM-DD form.

Press Run to see output

Check Your Understanding