2
import glob
import pandas as pd
import datetime

my_dates = ['Date']
sorted(my_dates, key=lambda x :datetime.datetime.strptime(x,'%m/%d/%Y'))

Getting the error in title. Not sure why. the date format in excel sheet is 1/2/2020 (m/d/yyyy) Tried many methods off google search and getting same error. Checked excel sheet to see if any dates written wrong but nope.

Python lists the column as object/list

  • Hello, can you print(x)? And by the way, `my_dates = ['Date']` means you've set `my_dates` as `a list` containing `1 string "Date"`. Maybe you forgot to add the DF first? `df['Date'].values` ? – mrbTT Feb 17 '20 at 19:27
  • ```print(x) Traceback (most recent call last): File "", line 1, in print(x) NameError: name 'x' is not defined``` – plshelpimpoor Feb 17 '20 at 19:29
  • Yeah, that error it's because the x is inside the lambda function. See my edit to my first comment. – mrbTT Feb 17 '20 at 19:30
  • it is unclear how your input data looks - do you mean something like `my_dates = df['Date']`? – FObersteiner Feb 17 '20 at 19:35
  • Tried this, same error. ```df = pd.DataFrame(ph, columns = ['E.T.A. DATE']) my_dates = df sorted(my_dates, key=lambda x :datetime.datetime.strptime(x,'%m/%d/%Y'))``` – plshelpimpoor Feb 17 '20 at 19:52
  • that does not clarify anything... please read the [ask] section and provide a [mre]. – FObersteiner Feb 17 '20 at 20:05
  • Nevermind got it working: ```df = pd.DataFrame(ph, columns = ['Date']) ph['Date'] = pd.to_datetime(df['Date''])``` This converted the string to date and time column – plshelpimpoor Feb 17 '20 at 20:20

2 Answers2

1

df = pd.DataFrame(ph, columns = ['Date']) ph['Date'] = pd.to_datetime(df['Date''])

  • Welcome to SO! From the comments, this looks like a great self-answer. However, it would really benefit from a little explanation to help future readers! – ti7 Feb 17 '20 at 22:25
0

In the first loop you've got x = 'Date' which can't be parsed as date, but it will when my_dates = ['10/28/2020']

frost-nzcr4
  • 1,540
  • 11
  • 16
  • But it is entire column containing dates, hence using the column header as "Date" which is how it is in excel. I tried changing to say 'ETA Date' and still same error. – plshelpimpoor Feb 17 '20 at 19:36
  • Then you must declare types, check this https://stackoverflow.com/a/37453925/5274713 – frost-nzcr4 Feb 17 '20 at 19:48