0

I am using pandas, and I have a column that contains datetime.

My DataFrame that contains Date values

How can I represent this datetime string in a proper way?

I did

df['Date'] = pd.to_datetime(df['Date'], format='%m%y%d')

But it gave me the error:

ValueError: time data 'May 11, 2015' does not match format '%m%y%d' (match)

Does anybody know how to solve that? Or is there a way that I can do this date transformation in a better way?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Ege Hurturk
  • 693
  • 1
  • 10
  • 12
  • 2
    "BONUS" is quite an unfortunate term & way to pack a 2nd different question here, without offering any info for it (where exactly does it happen?). Please avoid asking multiple questions in a single post - you can always open a separate question for your second issue (and link here, if necessary). Plus, question has nothing to do with `machine-learning` - kindly do not spam irrelevant tags (removed). – desertnaut Jun 15 '20 at 17:07
  • 1
    WHY would you think that `'%m%y%d'` is a match for `'May 11, 2015'` ?? – Patrick Artner Jun 15 '20 at 17:08
  • My purpose is to format the `May 11, 2015` in a way that is `2015-05-11`. – Ege Hurturk Jun 15 '20 at 17:09
  • kindly spend some time on https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes to read up the format strings for datetime formatting. You can change the default setting how pandas displays date - gimme a sek Ill search you the next duplicate: [how-to-change-the-datetime-format-in-pandas](https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas) – Patrick Artner Jun 15 '20 at 17:10
  • `'%b %d,%Y'` --> `%b` for Month name like Jan, Feb, Mar...`%d` for day, `%Y` for year with centry like 1990, 2020 etc. – Ch3steR Jun 15 '20 at 17:11
  • @PatrickArtner When I use `pd.to_datetime`, I get something like this: . `['2019-10-14T00:00:00.000000000'],`. – Ege Hurturk Jun 15 '20 at 17:18
  • This is a datetime object - exactly what you do when you convert the string into a datetime - if you want to get a STRING of format '%m%y%d you need to do both. first parse your string into a datetime object, then create a a string from the datetimeobject. `df['date2'] = pd.to_datetime(df['Date'], format='%b %d, %Y').dt.strftime('%m%y%d')` - `df = pd.DataFrame( {"date":["May 20, 2020"]})` + `df['date2'] = pd.to_datetime(df['date'], format='%b %d, %Y')` + `df['date3'] = df['date2'].dt.strftime('%d%m%Y')` – Patrick Artner Jun 15 '20 at 17:30

0 Answers0