DATE
202205
202204
202112
202202
202203
202201
I have a date column entered numerically. I have returned this column to object but I don't know how to make it datetime. I get an error because there is no Year-Month-Day on the roads I tried. Any suggestions?
CodePudding user response:
As mentioned in comment Python datetime module has a strptime() method which parses string to datetime objects. here is an example for your use case
from datetime import datetime
time_str = "202205"
format_str = "%Y%m"
parsed_date = datetime.strptime(time_str, format_str)
print(parsed_date)
this outputs
2022-05-01 00:00:00
please note that if your date string does have any day or time fields then the resultant object will be having the default values.
To learn more about datetime module and strptime method in specific refer to this article
CodePudding user response:
I solved my question with this answer
df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m', errors='coerce').dropna()