Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of days between 2 dates, excluding weekends

How can I calculate number of days between two dates excluding weekends?

like image 687
Mohammad Nadeem Avatar asked Sep 01 '10 05:09

Mohammad Nadeem


People also ask

How do you calculate the number of days between two dates excluding Sunday?

Here I can introduce a formula for counting days excluding Sundays during a date range. Select a blank cell, here is C2, and type this formula =B2-A2-INT((B2-A2-WEEKDAY(B2)+1)/7) into it, and then press Enter key, a date displayed.

How do I exclude weekends between two dates in SQL?

You Can simply use datediff function of sql. and then you can subtract weekends between those dates if any. For example check below query. And If You want to exclude holiday's too, then, You also can calculate holidays between start/end date and can subtract that from final selection.

How do I calculate days between dates in Excel and not including weekends?

=NETWORKDAYS(A2,B2) Then type Enter key, and you will count the number of workdays excluding Sundays and Saturdays between the two dates.


2 Answers

I think the cleanest solution is to use the numpy function busday_count

import numpy as np import datetime as dt  start = dt.date( 2014, 1, 1 ) end = dt.date( 2014, 1, 16 )  days = np.busday_count( start, end ) 
like image 78
Ben Avatar answered Sep 29 '22 06:09

Ben


>>> from datetime import date,timedelta >>> fromdate = date(2010,1,1) >>> todate = date(2010,3,31) >>> daygenerator = (fromdate + timedelta(x + 1) for x in xrange((todate - fromdate).days)) >>> sum(1 for day in daygenerator if day.weekday() < 5) 63 

This creates a generator using a generator expression which will yield the list of days to get from the fromdate to todate.

We could then create a list from the generator, filtering out weekends using the weekday() function, and the size of the list gives the number of days we want. However, to save having the whole list in memory which could be a problem if the dates are a long time apart we use another generator expression which filters out weekends but returns 1 instead of each date. We can then just add all these 1s together to get the length without having to store the whole list.

Note, if fromdate == todate this calculate 0 not 1.

like image 20
Dave Webb Avatar answered Sep 29 '22 06:09

Dave Webb