Source

weeklib / weeklib.py

#!/usr/bin/env python
#-*- coding: UTF-8 -*-


import datetime


class WeekDb(object):

    def __init__(self, year):

        if isinstance(year, basestring):
            year = int(year)
        self.__week_db = self.__init_db(year)
        self.__year = year


    def __init_db(self, year):

        if isinstance(year, basestring):
            year = int(year)

        start_day = datetime.date(year, 1, 1)
        stop_day = datetime.date(year, 12, 31)

        week_db = {}
        for x in range(0, (stop_day - start_day).days):
            date = start_day + datetime.timedelta(days=x)
            week_num = get_week_num(date)
            if week_num not in week_db:
                week_db[week_num] = []
            week_db[week_num].append(date)

        return week_db


    def __getitem__(self, x):

        if isinstance(x, basestring):
            x = int(x)

        return self.__week_db[x]


    def __cmp__(self, other):

        return cmp(self.__year, other.__year)


def get_week_num(date=None):

    if not date:
        date = datetime.date.today()
    elif isinstance(date, (tuple, list)):
        date = datetime.date(int(date[0]), int(date[1]), int(date[2]))
    elif isinstance(date, dict):
        date = datetime.date(int(date['year']), int(date['month']), int(date['day']))
    elif not isinstance(date, datetime.date):
        date = datetime.date(int(date.year), int(date.month), int(date.year))

    return date.isocalendar()[1]


if __name__ == '__main__':

    import sys

    argv = sys.argv[1:]
    args = len(argv)
    if args >= 1:
        week_num = argv[0]
        if args >= 2:
            year = sys.argv[1]
        else:
            year = datetime.date.today().year
        db = WeekDb(year)
        print db[week_num]
    else:
        print 'usage: python %s WEEK_NUM [YEAR]'