Home > Software design >  How can I format date time string which is not date time format so that I can use it with pd.to_date
How can I format date time string which is not date time format so that I can use it with pd.to_date

Time:08-13

I have a Pandas series of date time string. However, that date time string isn't properly formatted. Therefore, can I know how can I format the date time string in order to use it with pd.to_datetime()?

e.g. t = pd.Series(['20201023', '20201123', '20201012'])

Thank you.

CodePudding user response:

No need to pre-process the string. Use format='%Y%m%d' directly in pandas.to_datetime:

t = pd.Series(['20201023', '20201123', '20201012'])

out = pd.to_datetime(t, format='%Y%m%d')

to_datetime can also guess the format automatically in most cases:

out = pd.to_datetime(t)

output:

0   2020-10-23
1   2020-11-23
2   2020-10-12
dtype: datetime64[ns]

CodePudding user response:

pd.to_datetime can infer datetime properly

out = pd.to_datetime(t)
print(out)

0   2020-10-23
1   2020-11-23
2   2020-10-12
dtype: datetime64[ns]
  • Related