Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError when converting String to datetime

Tags:

python

I have a dataframe as follows, and I am trying to reduce the dataframe to only contain rows for which the Date is greater than a variable curve_enddate. The df['Date'] is in datetime and hence I'm trying to convert curve_enddate[i][0] which gives a string of the form 2015-06-24 to datetime but am getting the error ValueError: time data '2015-06-24' does not match format '%Y-%b-%d'.

              Date      Maturity      Yield_pct Currency
0       2015-06-24          0.25             na      CAD
1       2015-06-25          0.25   0.0948511020      CAD

The line where I get the Error:

df = df[df['Date'] > time.strptime(curve_enddate[i][0], '%Y-%b-%d')]

Thank You

like image 638
user131983 Avatar asked Dec 06 '25 05:12

user131983


2 Answers

You are using wrong date format, %b is for the named months (abbreviations like Jan or Feb , etc), use %m for the numbered months.

Code -

df = df[df['Date'] > time.strptime(curve_enddate[i][0], '%Y-%m-%d')]
like image 88
Anand S Kumar Avatar answered Dec 09 '25 16:12

Anand S Kumar


You cannot compare a time.struct_time tuple which is what time.strptime returns to a Timestamp so you also need to change that as well as using '%Y-%m-%d' using m which is the month as a decimal number. You can use pd.to_datetime to create the object to compare:

df = df[df['Date'] > pd.to_datetime(curve_enddate[i][0], '%Y-%m-%d')]
like image 33
Padraic Cunningham Avatar answered Dec 09 '25 15:12

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!