跳至内容
菜单
此问题已终结
1 回复
8549 查看

Hello to all, i just wonder why i am getting an error for my converted string into datetime.

I have these fields:

current_year  = form['year_id'][1]

date_range = datetime.strptime(str(current_year)+'-01-01','%Y-%m-%d').date()

total_month_elapsed = (book_list.date_from.year - date_range.year) * 12 + book_list.date_from.month - date_range.month

 

I don't know when date_range is read the terminal says:

    date_range = datetime.strptime(str(current_year)+'-01-01','%Y-%m-%d').date()
TypeError: must be string, not datetime.date

Any help is much appreciated.

形象
丢弃

The code as submitted seems to be fine. Maybe the problem is elsewhere. Please submit more code and also describe your issue further.

最佳答案

To find number of months, you could use relativedelta python package

from dateutil.relativedelta import relativedelta
from datetime import date
d1 = date(2001, 5, 1)
d2 = date(2012, 1, 1)
rd = relativedelta(d2, d1)
print "{0.years} years and {0.months} months".format(rd)

Output
10 years and 8 months

形象
丢弃