简体   繁体   中英

Weeks difference between two dates in python

How do I get the differences between two valid dates in weeks. I have googled many, but none are the one that I have been looking for

Say I have two dates:

02-Dec-2016 and 10-Jan-2017 .

I want it to provide me with output like following

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)

This is what you actualy want:

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)

It is somewhat surprising how complicated it is to compute the difference between two times in Python. The following code is for differences in minutes, but you can modify this to weeks or other attributes.

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM