Date strings to datetimes
EasyPandas Programs · 27 of 95
Write a pandas program to convert date strings in different formats into datetimes.
Input["2 Feb 2020", "5/11/2021", "7-8-2022"]
Output0 2020-02-02
1 2021-11-05
2 2022-08-07
dtype: datetime64[us]
Approach
pd.to_datetime(..., format="mixed", dayfirst=True).
Solution
Python
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 3format="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.
More pandas programs
← All 95 Pandas Programs