python - 如何确定Python中两个日期之间的月数?
问题描述
我有两列是 datetime64[ns] 对象。我正在尝试确定它们之间的月数。
这些列是:
city_clean['last_trip_date']
city_clean['signup_date']
格式为 YYYY-MM-DD
我试过了
from dateutil.relativedelta import relativedelta
city_clean['months_active'] = relativedelta(city_clean['signup_date'], city_clean['last_trip_date'])
并得到以下错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
有谁知道什么可能导致这个问题?我觉得这是计算月数的最准确方法。
解决方案
这是熊猫,对吧?试试这样:
# calculate the difference between two dates
df['diff_months'] = df['End_date'] - df['Start_date']
# converts the difference in terms of Months (timedelta64(1,’M’)- capital M indicates Months)
df['diff_months']=df['diff_months']/np.timedelta64(1,'M')
或者,如果您有适当的日期时间对象,
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
推荐阅读
- c# - 如何在 C# WPF MVVM 中获取 Datagrid 的多个选定行的值
- php - 在 PHP 中使用路由时在 URL 中传递参数
- mongodb - MongoDB: How can I change engine type (from B-Tree to LSM-Tree) of _id_ index?
- prolog - Prolog:将带括号的常量转换为字符串
- java - 以编程方式下载 SQLite 文件
- rust - StreamExt::forward 失败,错误为 `expected integer, found enum`std::result::Result`
- django - 在 s3 存储桶中上传图像需要太长时间
- javascript - 如果值为真,则显示表格
- javascript - How to use default parameters in a function without following the order at which parameters are declared in it
- aws-device-farm - 在 aws devicefarm 中调用 createUpload 是否实际上传文件?