Home > Software engineering >  ValueError: time data '04/19/19 08:46' does not match format '%m/%d/%Y %H:%M' (m
ValueError: time data '04/19/19 08:46' does not match format '%m/%d/%Y %H:%M' (m

Time:09-21

Order Date

0 04/19/19 08:46
2 04/07/19 22:30
3 04/12/19 14:38
4 04/12/19 14:38 5 04/30/19 09:27

This is my column in DataFrame and the type of the column is 'object'

df.dtypes

Order Date object

I am trying to convert it to date time with the bellow code but getting error.

df['Order Date']=pd.to_datetime(df['Order Date'], format='%m/%d/%y %H:%M')

I have tried multiple options but still getting error

ValueError: time data '04/19/19 08:46' does not match format '%m/%d/%y %H:%M' (match)

Please help me with this!

CodePudding user response:

no need to add format, pandas recognize it automatically:

df['Order Date'] = pd.to_datetime(df['Order Date'])

or use datetime instead:

import datetime

df['Date'] = df['Date'].map(lambda x: datetime.datetime.strptime(x, '%m/%d/%y %H:%M'))

if error is inevitable, or can't locate it, or don't know how to proceed, do this:

#example df with non datetime value
    Order Date
0   04/19/19 08:46
1   04/07/19 22:30
2   random text

df['Order Date2'] = pd.to_datetime(df['Order Date'], errors='coerce')

df 
    Order Date      Order Date2
0   04/19/19 08:46  2019-04-19 08:46:00
1   04/07/19 22:30  2019-04-07 22:30:00
2   random text     NaT

df.loc[df['Order Date2'].isna()] #isolate the row where error exist
    Order Date  Order Date2
2   random text NaT

CodePudding user response:

df['Order Date']=pd.to_datetime(df['Order Date'], format='%m/%d/%y %H:%M')

EDIT to reflect your comment:

Have you tried to do this?

df['Order Date']=pd.to_datetime(df['Order Date'])

Try this to print dates that dont fit the format

from datetime import datetime
for date_str in df["Order Date"]:
    try:
        a = datetime.strptime(date_str, '%m/%d/%y %H:%M')
    except ValueError:
        print(date_str)
  • Related