简体   繁体   中英

Value error when converting different date formats to one single format

Hello I have a date column on my dataset which looks like this

import pandas as pd 

# initialize list of lists 
data = [['2020-11-05 00:00:00'], ['4/24/20'],['5/26/19'], ['2019-08-12 00:00:00']] 

# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['date']) 

# print dataframe. 
df

Now I want to convert all the date format to on single format of dd-mm-yyyy , which I have tried with this code

df['date']= df['date'].astype(str)

import datetime

def guess_date(string):
    for fmt in ["%m/%d/%Y", "%d-%m-%Y", "%Y-%m-%d"]:
        try:
            return datetime.datetime.strptime(string, fmt).date()
        except ValueError:
            continue
    raise ValueError(string)

for sample in df['date']:
    d = guess_date(sample)
    print(d.strftime("%d-%m-%y"))

I get this error when I try to run it ValueError: 2020-11-05 00:00:00 . Kindly anyone to help on this?

I expect all date formats to be one as dd-mm-yyyy

You should add two formats more in formats array. The changed code is as follows.

import pandas as pd
import datetime

data = [['2020-11-05 00:00:00'], ['4/24/20'],['5/26/19'], ['2019-08-12 00:00:00']]
df = pd.DataFrame(data, columns = ['date']) 
df['date']= df['date'].astype(str)

print(df)

def guess_date(string):
    # added "%m/%d/%y" and "%Y-%m-%d %H:%M:%S"
    for fmt in ["%m/%d/%Y", "%m/%d/%y", "%d-%m-%Y", "%Y-%m-%d", "%Y-%m-%d %H:%M:%S"]:  
        try:
            return datetime.datetime.strptime(string, fmt).date()
        except ValueError:
            continue
    raise ValueError(string)

for sample in df['date']:
    d = guess_date(sample)
    print(d.strftime("%d-%m-%y"))

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