How to deal with multiple date string formats in a python series

后端 未结 3 422
轮回少年
轮回少年 2021-01-05 17:41

I have a csv file which I am trying to complete operations on. I have created a dataframe with one column titled \"start_date\" which has the date of warranty start. The pro

3条回答
  •  暖寄归人
    2021-01-05 18:07

    Unfortunately you just have to try each format it might be. If you give an example format, strptime will attempt to parse it for you as discussed here.

    The code will end up looking like:

    import datetime    
    
    POSSIBLE_DATE_FORMATS = ['%m/%d/%Y', '%Y/%m/%d', etc...] # all the formats the date might be in
    
    for date_format in POSSIBLE_DATE_FORMATS :
        try:
            parsed_date = datetime.strptime(raw_string_date, date_format) # try to get the date
            break # if correct format, don't test any other formats
        except ValueError:
            pass # if incorrect format, keep trying other formats
    

提交回复
热议问题