从两个日期列中查找日期

时间:2018-08-16 21:19:23

标签: python datetime spyder

我有两列的开始和结束日期; [这些列的摘要] [1] S

ervice Start Day    Service Completion Day
2015-02-16  2015-02-16
2015-06-17  2015-06-18
2015-06-06  2015-06-06
2015-08-08  2015-08-08
2015-08-03  2015-08-21
2015-07-25  2015-07-25
2015-08-17  2015-08-17
2015-07-30  2015-09-24

我想逐行计算所有这些日期之间的差异,并将它们放在另一列中。

我尝试过这种方式;

Df['Service Completion Day'] = date(Df['Service Completion Day'])

Df['Service Request Day'] = date(Df['Service Request Day'])

Df.assign(Days = Df['Service Completion Day'] - Df['Service Request Day'])

但这不起作用。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

作为输入,您有两个字符串,例如'2015-02-12''2015-02-16'。您应该将它们解析为datetime.date个对象,然后计算差异。

例如:

import datetime

date_string_1 = '2015-02-12'
date_string_2 = '2015-02-16'

date1 = datetime.datetime.strptime(date_string_1, '%Y-%m-%d').date()
date2 = datetime.datetime.strptime(date_string_2, '%Y-%m-%d').date()

print (date2-date1)  # prints: 4 days, 0:00:00

difference_in_days = (date2-date1).days

print(difference_in_days)  # prints: 4