'Convert string Month-Year to datetime in pandas dataframe
I have a column in my dataframe called 'date' as below:
Date
Jan-1981
Feb-1981
Mar-1981
.
.
Sep-2005
.
Dec-2008
Is there a way to convert this into datetime format so the default format is DD/MM/YYYY where DD is always 01. eg.
Expected 'Date'
01-01-1981
01-02-1982
.
.
.
.
.
01-12-2008
Solution 1:[1]
If for some reason pd.to_datetime doesnt parse dates directly (happened to me once where the date format of data was YYYYMMDD with no separators at all) you can get away by using datetime.strptime first, in your case :
import datetime as dt
df['Date'] = pd.to_datetime(df['Date'].apply(lambda x: dt.strptime(x, '%b-%Y')))
Note : the reason you still need to use pd.to_datetime is because the datetime's and pandas' date-data type are different :
datetime.strptime returns a datetime object cf the documentation
pandas.to_datetime returns a Timestamp or datetime64 cf pandas' documentation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
