简体   繁体   English

Pandas - 月年格式的两个日期之间的月数

[英]Pandas - Number of Months Between Two Dates in Month year format

I have dates in format of Jan-09, Jan-18 where 09 and 18 are years.我的日期格式为 Jan-09、Jan-18,其中 09 和 18 是年份。 How do I code to find the number of months between these two days.我如何编码以查找这两天之间的月数。 I tried using this code:我尝试使用此代码:

ata4['mob_try'] = ((data4.last_pymnt_date - data4.issue_date)/np.timedelta64(1, 'M')).

data4['mob'] = data4['mob_try'].astype(int)

but there is an error "unsupported operand type(s) for -: 'str' and 'str'" how do I resolve this??但是有一个错误“-:'str'和'str'不支持的操作数类型”我该如何解决这个问题?

You can use datetime and relativedelta to achieve this:您可以使用datetimerelativedelta来实现这一点:

from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('Jan-09'), '%b-%y')
date2 = datetime.strptime(str('Jan-18'), '%b-%y')
r = relativedelta.relativedelta(date2, date1)

total_months = r.years*12 + r.months

print("Total months: {0}".format(total_months))

On which line this error occurs?这个错误发生在哪一行? If it's on the 1st line, maybe last_pymnt_date or issue_date columns are still stored as int .如果它在第一行,可能last_pymnt_dateissue_date列仍存储为int In this case, you must use pd.to_datetime() on each one first.在这种情况下,您必须先在每个上使用pd.to_datetime()

This example should work:这个例子应该工作:

d1 = pd.to_datetime(data4.last_pymnt_date) d1 = pd.to_datetime(data4.last_pymnt_date)

d2 = pd.to_datetime(data4.issue_date) d2 = pd.to_datetime(data4.issue_date)

data4['mob'] = (d1 - d2) // np.timedelta64(1, 'M')) data4['mob'] = (d1 - d2) // np.timedelta64(1, 'M'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM