简体   繁体   中英

How to convert string year-month to datetime in python

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?

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

I solved my question with this answer

df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m', errors='coerce').dropna()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM