python中两个日期之间的周差异

时间:2016-10-07 02:40:54

标签: python

如何在几周内获得两个有效日期之间的差异。我用Google搜索了很多,但没有一个是我一直在寻找的

说我有两个日期:

  

2016年12月2日 2017年1月10日

我希望它能为我提供如下的输出

02-Dec-2016 - 04-Dec-2016 (2 days) (2 days before monday comes)
05-Dec-2016 - 08-Jan-2017 (5 weeks) (starts from monday-sunday)
08-Jan-2017 - 10-Jan-2017 (2 days) (2 days after monday has gone)

2 个答案:

答案 0 :(得分:1)

这是你真正想要的:

import datetime


def diff(d1, d2):
    result = []
    delta = datetime.timedelta(days=0)
    day = datetime.timedelta(days=1)

    while d1.weekday() != 0:
        d1 += day
        delta += day
    result.append((d1 - delta, d1 - day))

    weeks, days = divmod((d2 - d1).days, 7)
    d3 = d1 + datetime.timedelta(weeks=weeks)
    d4 = d3 + datetime.timedelta(days=days)

    result.append((d1, d3 - day))
    result.append((d3, d4))
    return result


d1 = datetime.date(2016, 12, 2)
d2 = datetime.date(2017, 01, 10)

for i,j in diff(d1,d2):
    print '{} - {} ({} days)'.format(datetime.datetime.strftime(i, "%d-%b-%Y"), datetime.datetime.strftime(j, "%d-%b-%Y"), (j-i).days + 1)

# 02-Dec-2016 - 04-Dec-2016 (3 days)
# 05-Dec-2016 - 08-Jan-2017 (35 days)
# 09-Jan-2017 - 10-Jan-2017 (2 days)

答案 1 :(得分:0)

在Python中计算两次之间的差异有点复杂,这有点令人惊讶。以下代码用于分钟的差异,但您可以将其修改为周或其他属性。

# Compute the difference between two time values
import datetime 
df = pd.DataFrame({'ATime1' : ['8/26/2016 10:00','8/26/2016 10:01','8/26/2016 10:02','8/26/2016 10:03'], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50], 'ATime2' : ['8/26/2016 10:01','8/26/2016 10:02','8/26/2016 10:03','8/26/2016 10:04']})
s1 = pd.Series(df['ATime1'])  # Select one column of the dataframe and convert to a Series
s2 = pd.Series(df['ATime2'])
s1 = pd.to_datetime(s1)   #  Convert the Series object values to datetime values
s2 = pd.to_datetime(s2)
m1 = s1.dt.minute       #  Select minutes from the datetime values
m2 = s2.dt.minute
t1 = m1.loc[1]    #  Select the first minutes value in the column
t2 = m2.loc[1]
t1 = int(t1)       # Convert minutes to integer
t2 = int(t2)
diff = t2 - t1
if t2 > t1:
    print "ATime2 starts later than Atime1 by ", diff, " minute(s)."
else:
    print "ATime1 starts later than Atime2 by ", diff, " minute(s)."
    print t1, t2