Reputation: 9024
I'm familiar with the timedelta method in Python for subtracting days from the current date (below); however I'm curious how I could go about getting it to automatically skip over weekends.
from datetime import datetime, timedelta
target_date = datetime.today() - timedelta(days=dayoffset)
So for example, 2019-Oct-08 less 3 days would be 2019-Oct-03 (as the 5th and 6th are weekend days). Thank you!
Upvotes: 0
Views: 1308
Reputation: 1083
You can try datetime.weekday()
, it returns date to a value from 0-6, while 5 and 6 are the weekend days.
from datetime import datetime, timedelta
def diff_day(start, end):
delta = timedelta(days=1)
d = start
diff = 0
weekend = [5, 6]
while d < end:
if d.weekday() not in weekend:
diff += 1
d += delta
return diff
>>>start = datetime(2019,10,3)
>>>end = datetime(2019,10,8)
>>>diff_day(start, end)
3
Upvotes: 2