如何计算从日期时间到今天的天数?

How to calculate the number of days from a datetime until today?

我有一个带有日期列的数据框,表示为 ndarray 对象。我想集群化数据框,我决定将此列中的每个字符串(如“2009-01-04”)转换为 int。考虑到最后日期是今天的日期,我如何将它表示为最近几天?我在使用“to_datetime”方法时遇到了一些问题。

index col1 col2  date
 0     a    34  '2009-01-04'
 1     a    21  '2009-01-05'
 2     b    8   '2009-01-06'

谢谢

我认为您需要将日期转换为日期时间,然后从右侧减去 Series.rsub today dates, last convert output timedeltas to days by Series.dt.days:

df['new'] = pd.to_datetime(df['date']).rsub(pd.Timestamp('now').floor('d')).dt.days
print (df)
  col1  col2          date   new
0    a    34  '2009-01-04'  4282
1    a    21  '2009-01-05'  4281
2    b     8  '2009-01-06'  4280