Dates
Parse Date
Convert date strings from a regional format (MM/DD/YYYY) into ISO 8601
strings (YYYY-MM-DD). By hand, parse each string with
datetime.strptime using an explicit format code and call .isoformat()
on the result. With pandas, pd.to_datetime infers the format and the
datetime64 Series normalises to ISO via .dt.strftime.
By hand
With pandas
pd.to_datetime(df['d']) infers the MM/DD/YYYY format from the data and
returns a datetime64[ns] Series. .dt.strftime('%Y-%m-%d') converts each
timestamp back to a plain ISO string for the RESULT.
naive.py
import datetime
date_strs = ['05/10/2023', '08/25/2023', '01/03/2024', '06/18/2024']
result = []
for s in date_strs:
d = datetime.datetime.strptime(s, '%m/%d/%Y').date()
result.append(d.isoformat())
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
date_strs = ['05/10/2023', '08/25/2023', '01/03/2024', '06/18/2024']
df = pd.DataFrame({'d': date_strs})
s = pd.to_datetime(df['d'])
result = s.dt.strftime('%Y-%m-%d').tolist()
print('index:', s.index.tolist())
print('dtype:', s.dtype)
print('values:', s.dt.strftime('%Y-%m-%d').tolist())
print('RESULT:', result)
index: [0, 1, 2, 3]
dtype: datetime64[ns]
values: ['2023-05-10', '2023-08-25', '2024-01-03', '2024-06-18']
RESULT: ['2023-05-10', '2023-08-25', '2024-01-03', '2024-06-18']
Implementation notes
pd.to_datetimeinfers many common formats automatically. For ambiguous inputs (e.g.'01/02/03') or production pipelines, passformat='%m/%d/%Y'to be explicit and avoid mis-parsing.- Date equality: both halves produce plain Python strings so RESULT
comparison is straightforward string equality — no
datetime.datevsTimestampconversion needed. - Cross-reference:
parse-date-column(python-pandas ch09) for the companion lesson covering.dtaccessor workflows after parsing; this lesson focuses on the format-normalization step for messy inputs.