尝试将一列日期减去另一个日期

时间:2018-10-15 09:54:25

标签: python pandas numpy datetime

我有日期:

  var addresses = context.Addresses;
  var contracts = context.Contracts;

  foreach(var a in contracts) {
      new MyDto() {
        AddressId = addresses.Where(x => a.AddressId == x.AddressId).Select(y => y.AddressNumber);
        AddressName = addresses.Where(x => a.AddressId == x.AddressId).Select(y => y.FullName);
        Date= a.Date,
        AnotherDate = a.AnotherDate,
        Text = a.Text,
        VerweisAdrId = addresses.Where(x => a.VerweisAdrId == x.AddressId).Select(y => y.AddressNumber);
        VerweisAdrName = addresses.Where(x => a.VerweisAdrId == x.AddressId).Select(y => y.FullName);
      }
  }

我想在日期列中减去dateTo=pd.to_datetime('today').strftime('%Y-%m-%d')

dateTo

所需的输出将是带有减法输出的新列 number dates coord AC 10 2018-07-10 11.54 AC 10 2018-07-11 11.19 AN 5 2018-07-12 69.40 。我希望此输出为整数。

我尝试的是在Pandas: Subtracting two date columns and the result being an integer处给出的答复:

df['datepond']

在numpy 1.12.1版本中,它工作得很好,但即时通讯现在是numpy 1.15.2,并且输出

df['datepond']=(pd.Timestamp(dateTo)-pd.to_datetime(df['dates']))/ np.timedelta64(1, 'D')

如何获得所需的输出?

1 个答案:

答案 0 :(得分:4)

您可以尝试Timestamp.floor删除时间,并将时间增量转换为天Series.dt.days

df['datepond']= (pd.to_datetime('today').floor('d') - pd.to_datetime(df['dates'])).dt.days
print (df)
    number       dates  coord  datepond
AC      10  2018-07-10  11.54        97
AC      10  2018-07-11  11.19        96
AN       5  2018-07-12  69.40        95