Python Practice › Pandas Programs › Program 27
Date strings to datetimes
Write a pandas program to convert date strings in different formats into datetimes.
Input
["2 Feb 2020", "5/11/2021", "7-8-2022"]
Output
0 2020-02-02 1 2021-11-05 2 2022-08-07 dtype: datetime64[us]
Approach
pd.to_datetime(..., format="mixed", dayfirst=True).
Solution
import pandas as pds = pd.Series(["2 Feb 2020", "5/11/2021", "7-8-2022"])print(pd.to_datetime(s, format="mixed", dayfirst=True))Output
0 2020-02-02 1 2021-11-05 2 2022-08-07 dtype: datetime64[us]
Line by line
Line 3
format="mixed" parses each value separately; dayfirst=True reads 5/11/2021 as 5 November.
Learn the concept
New to this topic? Read the lesson, then come back.