my date format come in format 11122020
(ddmmyyyy) in a pandas column.
I use
datapdf["wholetime"]=pd.to_datetime(datapdf["wholetime"],format='%d%m%Y)
to convert to time and do processing on the time.
recently my code failed for date 3122020 as
ValueError: day is out of range for month
python is interpreting as 31 2 2020 instead of 3 12 2020 which is causing the error. Any one have solution for this?
One way would be to use str.zfill
to ensure that date is in 8 digits:
s = pd.Series(["11122020", "3122020"])
pd.to_datetime(s.str.zfill(8), format="%d%m%Y")
Output:
0 2020-12-11
1 2020-12-03
dtype: datetime64[ns]
Note that this answer only concerns about missing 0 in the day. It won't be able to parse more ambiguous items such as 332020
, where the month part also requires heading 0.