🎓 A1Learner
🔍
0 of 50 lessons completed

Reading Dates

Dates in a CSV file start as plain text. The parse_dates option turns a date column into real dates while reading.

Parse dates while reading

The parse_dates option names the date column. The dates print in the same shape, but they are real dates now.

import io
import pandas as pd

small_csv = """order_id,date,product
101,2026-01-05,Tea
102,2026-01-06,Coffee
103,2026-01-07,Mug"""
df = pd.read_csv(io.StringIO(small_csv), parse_dates=["date"])
print(df)

Turn date words into dates

The to_datetime function takes a list of date words. It gives back dates with their kind shown at the end.

import pandas as pd

dates = pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"])
print(dates)

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV), parse_dates=["date"])
print(sales)

Key points

  • Use parse_dates to turn a date column into dates while reading.
  • Pass a list of column names to parse_dates, like ["date"].
  • A date column then holds dates, not plain text.
  • Use pd.to_datetime to turn a list of date words into dates.
  • Print the frame to see the dates in place.

In this example, the sales CSV is read with parse_dates set to a list with one name, date. The date column becomes real dates while reading. The print shows all twelve rows with the dates in place.

Note

Real dates keep their calendar order, so the 5th of January comes before the 6th.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which option turns a date column into real dates while reading a CSV file?