user131983
user131983

Reputation: 3927

ValueError when converting String to datetime in Python

I have a Dataframe df and I am trying to find the difference, in months, between df['maturity_dt'] and todays date and use the code below to do this, but I get the error ValueError: time data '2015-12-31 00:00:00.0' does not match format '%Y-%b-%d %H:%M:%S'. I guess I don't know how to refer to the last 0 in 00:00:00.0

def months_to_maturity_func(d1, d2):
    return abs((d2 - d1).months)

todays_date = datetime.date.today()

for (i,row) in df.iterrows():
    row['months_to_maturity'] = months_to_maturity_func(todays_date, datetime.datetime.strptime(row['maturity_dt'], '%Y-%b-%d %H:%M:%S'))

Thank You

Upvotes: 0

Views: 161

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90889

You are using the wrong format , try using - %Y-%m-%d %H:%M:%S.%f .

%b is for three letter month abbreviations like - Jan , Feb , etc.

And use %f at the end for microseconds.

Upvotes: 2

Related Questions