0

I am trying to convert a set of date time data within Python.

The data frame within the pandas library looks like the following:

     dates    dates2        dates3
2011-05-09  20110509    05.2011.09
2011-09-23  20110923    09.2011.23
2012-04-30  20120430    04.2012.30
2014-09-12  20140912    09.2014.12

Is there an elegant way to automatically convert this data from an object into a date time data type, without having to loop through each element within each column?

tinder
  • 35
  • 7
  • 1
    `df.dates = pd.to_datetime(df.dates, "%Y-%m-%d")`. `to_datetime` can also try to infer the format but I'm not sure it if will be successful in this case. There's plenty of info for converting to datetime online already, have you tried researching this? – roganjosh Nov 21 '17 at 03:31
  • 1
    Possible duplicate of [Convert DataFrame column type from string to datetime](https://stackoverflow.com/questions/17134716/convert-dataframe-column-type-from-string-to-datetime) – roganjosh Nov 21 '17 at 03:40
  • @roganjosh I have tried that, the issue is with the second column. It has no punctuation to seperate the years, months and days so it produces the following error:ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing – tinder Nov 21 '17 at 03:42
  • You just specify the format. `%Y%m%d`. – roganjosh Nov 21 '17 at 03:42
  • fair enough, but my question was how to automatically do it. say in one instance the second column wasn't yyyymmdd but mmddyyyy and the other two columns remained the same. is there any function that can infer the date time without any tedious try and except conditions? – tinder Nov 21 '17 at 03:44
  • As I said, `to_datetime` [does have an infer datetime format option](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html) but I think it will fail, especially with `dates3`. In your example the formats are consistent for each column so there should be no need for exception handling. You can also specify how you want it to handle parse errors. – roganjosh Nov 21 '17 at 03:47
  • @roganjosh pardon me asking, but I am fairly new to python. how would you go about specifying how you want to handle parse errors? – tinder Nov 21 '17 at 03:51
  • `df.dates = pd.to_datetime(df.dates, errors='coerce', infer_datetime_format=True)` would be the approach if you want to have a shot at inferring the format without specifying it, and stopping errors from crashing the code. You can see what `coerce` is doing from my link in previous comment. – roganjosh Nov 21 '17 at 03:54

0 Answers0