Search code examples
python-3.xpandasstrftimestring-to-datetime

pandas to_datetime could not convert non zero-padded strings to datetime


I tried to convert the following series s of strings into datetime,

12118
12218
11318
10418

s = s.str.zfill(5)
format = {'%m%-d%y': 5}

L = [pd.to_datetime(s.str[:v], format=k, errors='coerce') for k, v in format.items()]

[0    12118
 1    12218
 2    11318
 3    10418
 dtype: object]

I am wondering how to covert them into

2018-12-01
2018-12-02
2018-11-03
2018-10-04

Solution

  • IIUC

    pd.to_datetime(df,format='%m%d%y')
    Out[210]: 
    0   2018-12-01
    1   2018-12-02
    2   2018-11-03
    3   2018-10-04
    Name: x, dtype: datetime64[ns]