How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetimes?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
If you have a mixture of formats in your date, don't forget to set
infer_datetime_format=True
to make life easierdf['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)
Source: pd.to_datetime
or if you want a customized approach:
You can use the following if you want to specify tricky formats:
More details on
format
here:The easiest way is to use
to_datetime
:It also offers a
dayfirst
argument for European times (but beware this isn't strict).Here it is in action:
You can pass a specific format:
If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.
df['date'] = df['date'].astype('datetime64[ns]')
or use datetime64[D] if you want Day precision and not nanoseconds
print(type(df_launath['date'].iloc[0]))
yields
<class 'pandas._libs.tslib.Timestamp'>
the same as when you use pandas.to_datetimeYou can try it with other formats then '%Y-%m-%d' but at least this works.