Number of working days in python

Given the start date, how can I determine how many “working weeks” Python had? I can't just divide by 7, because that will not give me the correct answer.

An example is the start date of August 1, 2012 to the current date (August 13, 2012), which will be displayed in 3 weeks.

I'm basically trying to find out from the very beginning of the football season what the current week is (integer).

I tried communicating with the Pythons datetime module, but it was useless.

+5
source share
4 answers

datetime.weekday, datetime.isoweekday datetime.isocalendar, .

, :

def week_difference(start, end):
    assert start <= end
    start_year, start_week, start_dayofweek = start.isocalendar()
    end_year, end_week, end_dayofweek = end.isocalendar()

    return ((end_year - start_year) * 52) - start_week + end_week

:

import datetime as dt
# same week
In [1]: week_difference(dt.datetime(2012, 8, 1),  dt.datetime(2012, 8, 1))
Out[1]: 0

# your example (see note below) 
In [2]: week_difference(dt.datetime(2012, 8, 1),  dt.datetime(2012, 8, 13))
Out[2]: 2

# across years
In [3]: week_difference(dt.datetime(2011, 8, 1),  dt.datetime(2012, 8, 13))
Out[3]: 54

# year boundary: second last business week of 2011, to first business week of 2012
# which is the same business week as the last business week of 2011
In [4]: week_difference(dt.datetime(2011, 12, 20),  dt.datetime(2012, 1, 1))
Out[4]: 1

In [5]: week_difference(dt.datetime(2011, 12, 18),  dt.datetime(2012, 1, 1))
Out[5]: 2

1 , .

+7

datetime...

import datetime
today = datetime.datetime.now()
start = datetime.datetime(2012, 9, 5)

... isocalendar...

today.isocalendar()
>>> (2012, 33, 1)
start.isocalendar()
>>> (2012, 36, 3)

3- , . , " " ( ). .

+2

:

datetime.date.isocalendar(datetime.date.today())[1] - datetime.date(2012, 8, 1).isocalendar()[1] + 1
0
source

My single line expander includes the borders of the year:

start_date = datetime.date(2012, 8, 1)
print ((datetime.date.isocalendar(datetime.date.today())[0]-datetime.date.isocalendar(start_date)[0])*52)+(datetime.date.isocalendar(datetime.date.today())[1]-datetime.date.isocalendar(start_date)[1])+1
>>> 3

Note. This function will still return negative values ​​if start_date is in the future (from today)!

0
source

All Articles