-1

I wish to convert a string in pandas to datetime, but conversion fails.

My data has the format for example 06.12.2015 This means day.month.year

try:
    #Code that may raise an error
    df['date']= pd.to_datetime(df['date'], format='%d%m%Y')
    #Raising your own errors
    raise Exception("Error converting date")
except Exception as e: 
    #code to run if error occurs
    logging.error("Exception occurred  " + filename , exc_info=True)
    #code to run if error is raised
    print("Conversion not work.")
else:
    df['date']= pd.to_datetime(df['date'], format='%d.%m.%y')

then

print(df.dtypes)

gives object and exception is raised.

Can someone help me please?

Lee
  • 29,398
  • 28
  • 117
  • 170
Smiley
  • 479
  • 2
  • 5
  • 15
  • you can replace the `.` with `''` : `pd.to_datetime(s.str.replace('.',''), format='%d%m%Y')` , tested with `s = pd.Series(['06.12.2015','06122015'])` then `pd.to_datetime(s.str.replace('.',''), format='%d%m%Y')` – anky Mar 14 '20 at 16:31
  • I am not having a series but a table column with date that just has the format 11.02.1984 , how would the solution look like – Smiley Mar 14 '20 at 17:09
  • a table column? isnt that a series? replace `s` with `table['column']` – anky Mar 14 '20 at 17:11
  • 1
    `df['date']=pd.to_datetime(df['date'],format='%d.%m.%Y')` !!! – Lee Mar 14 '20 at 17:11
  • Are you able to create a "reprex"? https://stackoverflow.com/help/minimal-reproducible-example – Lee Mar 14 '20 at 17:36
  • **Please provide the entire error message, as well as a [mcve].** Be careful about using `except Exception` like that, see https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except. – AMC Mar 14 '20 at 20:55

1 Answers1

0

Given yourfile.dat:

string,date,number
a string,06.12.2015,1.0
a string,06.12.2015,2.0

read in:

b=pd.read_csv('yourfile.dat')

You need to put .s in the date format, and you need a capital Y to read in a four digit year.:

b['date']=pd.to_datetime(b['date'],format='%d.%m.%Y')
Lee
  • 29,398
  • 28
  • 117
  • 170
  • df['date']= pd.to_datetime(df['date'], format='%d.%m.%Y') where exactly is the difference? I already read the csv before. The input data has the format 01.12.1984 – Smiley Mar 14 '20 at 17:03
  • both does not work! this is not the problem, as you can see above its exactly what I did. I tried both and the data matches. – Smiley Mar 14 '20 at 17:14
  • @Smiley It's hard to tell exactly what you did from just the question. A simplifed example and the full error trace might help... "I tried both and the data matches" I'm afraid I'm not sure what you are referring to here... – Lee Mar 14 '20 at 17:45