How can I get the current week using Python?

27,253

Solution 1

Beware! If you want to define YOUR OWN week numbers, you could use the generator expression provided in your first question which, by the way, got an awesome answer). If you want to follow the ISO convention for week numbers, you need to be careful:

the first calendar week of a year is that one which includes the first Thursday of that year and [...] the last calendar week of a calendar year is the week immediately preceding the first calendar week of the next calendar year.

So, for instance, January 1st and 2nd in 2010 were NOT week one of 2010, but week 53 of 2009.

Python offers a module for finding the week number using the ISO calendar:

Example code:

h[1] >>> import datetime
h[1] >>> Jan1st = datetime.date(2010,1,1)
h[1] >>> Year,WeekNum,DOW = Jan1st.isocalendar() # DOW = day of week
h[1] >>> print Year,WeekNum,DOW
2009 53 5

Notice, again, how January 1st 2010 corresponds to week 53 of 2009.

Using the generator provided in the previous answer:

from datetime import date, timedelta


def allsundays(year):
    """This code was provided in the previous answer! It's not mine!"""
    d = date(year, 1, 1)                    # January 1st                                                          
    d += timedelta(days = 6 - d.weekday())  # First Sunday                                                         
    while d.year == year:
        yield d
        d += timedelta(days = 7)

Dict = {}
for wn,d in enumerate(allsundays(2010)):
    # This is my only contribution!
    Dict[wn+1] = [(d + timedelta(days=k)).isoformat() for k in range(0,7) ]

print Dict

Dict contains the dictionary you request.

Solution 2

There is a 3 lines method I developed after read that question:

from datetime import timedelta

def get_week_dates(base_date, start_day, end_day=None):
    """
    Return entire week of dates based on given date limited by start_day and end_day.
    If end_day is None, return only start_day.

    >>> from datetime import date
    >>> get_week_dates(date(2015,1,16), 3, 5)
    [datetime.date(2015, 1, 14), datetime.date(2015, 1, 15), datetime.date(2015, 1, 16)]

    >>> get_week_dates(date(2015,1,15), 2, 5)
    [datetime.date(2015, 1, 13), datetime.date(2015, 1, 14), datetime.date(2015, 1, 15), datetime.date(2015, 1, 16)]
    """
    monday = base_date - timedelta(days=base_date.isoweekday() - 1)
    week_dates = [monday + timedelta(days=i) for i in range(7)]
    return week_dates[start_day - 1:end_day or start_day]

Use get_week_dates(date.today(), 1, 7) to get current week dates.

Solution 3

current_week = datetime.datetime.now().isocalendar()[1]

Solution 4

Here's some code:

import datetime

now = datetime.datetime.now()

now_day_1 = now - datetime.timedelta(days=now.weekday())

dates = {}

for n_week in range(3):
    dates[n_week] = [(now_day_1 + datetime.timedelta(days=d+n_week*7)).strftime("%m/%d/%Y") for d in range(7)]

print dates

prints:

{
 0: ['01/04/2010', '01/05/2010', '01/06/2010', '01/07/2010', '01/08/2010', '01/09/2010', '01/10/2010'], 
 1: ['01/11/2010', '01/12/2010', '01/13/2010', '01/14/2010', '01/15/2010', '01/16/2010', '01/17/2010'], 
 2: ['01/18/2010', '01/19/2010', '01/20/2010', '01/21/2010', '01/22/2010', '01/23/2010', '01/24/2010']
}

Solution 5

You could use the datetime module. You can specify the format and everything. Here's the link: http://docs.python.org/library/datetime.html

Look into datetime.datetime( params ) and datetime.timedelta( params ). Hope it all goes well ;-)

Example:

import datetime

numweeks = 5
start_date = datetime.datetime(year=2010,month=1,day=4)    

weeks = {}

offset = datetime.timedelta(days=0)
for week in range(numweeks):
   this_week = []
   for day in range(7):
        date = start_date + offset
        date = date.strftime( some_format_string )
        this_week.append( date )
        offset += datetime.timedelta(days=1)
   weeks[week] = this_week 
Share:
27,253
rmontgomery429
Author by

rmontgomery429

Updated on June 24, 2020

Comments

  • rmontgomery429
    rmontgomery429 almost 4 years

    Using Python...

    How can I get a list of the days in a specific week?

    Something like...

    {
    '1' : ['01/03/2010','01/04/2010','01/05/2010','01/06/2010','01/07/2010','01/08/2010','01/09/2010'],  
    '2' : ['01/10/2010','01/11/2010','01/12/2010','01/13/2010','01/14/2010','01/15/2010','01/16/2010'] 
    }
    

    The key of the dictionary in this example would be the week number.