0

Anyone has some suggestions on how to convert below "1/1/08" to "2008-01-01"?

I Have tried datetime and strptime

datetime.strptime(str(Date_data['CALENDAR_DATE']), '%m/%d/%y').strftime('%m/%d/%Y')

Error says not match. I guess I need to remove \n1. However it is a dynamic number.How to do that ?

ValueError: time data '0        1/1/08\n1        1/2/08\n2        1/3/08\n3        1/4/08\n4        1/5/08\n         ...   \n5866    1/23/24\n5867    1/24/24\n5868    1/25/24\n5869    1/26/24\n5870    1/27/24\nName: CALENDAR_DATE, Length: 5871, dtype: object' does not match format '%m/%d/%y'

sample data:

CALENDAR_DATe: 1/1/08, 1/2/08
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
learnR19
  • 1
  • 1
  • You convert the pandas `Series` into a string `str(Date_data['CALENDAR_DATE'])` which does not allow you to convert the types as expected. As we can see there's a lot of extra information like the index, dtype and length in the output from `str(Date_data['CALENDAR_DATE'])`. This makes parsing difficult. – Henry Ecker Oct 18 '21 at 03:42
  • You should parse [to_datetime](https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html) first, then use the `dt` accessor to change back to strings with [dt.strftime](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html) like [this answer](https://stackoverflow.com/a/38067805/15497888) recommends `pd.to_datetime(Date_data['CALENDAR_DATE'], format='%m/%d/%y').dt.strftime('%Y-%m-%d')` <- update format strings to whatever is needed. – Henry Ecker Oct 18 '21 at 03:43
  • @HenryEcker. it works! many thanks – learnR19 Oct 18 '21 at 20:02

0 Answers0