Source

weeklib / weeklib.py

Full commit
#!/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)

        if not isinstance(year, int):
            raise TypeError('year must be integers or str that contains only numbers')

        start_day = datetime.date(year, 1, 1)
        stop_day = datetime.date(year + 1, 1, 1)

        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)

        if not isinstance(x, int):
            raise TypeError('indices must be integers or str that contains only numbers')

        if x < 0:
            x = len(self.__week_db) +  x + 1

        if x <= 0 or x > len(self.__week_db):
            raise IndexError('index out of range')

        return self.__week_db[x]


    def __cmp__(self, other):

        return cmp(self.__year, other.__year)


def get_week_num(date=None, iso=False):

    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))

    if iso:
        return date.isocalendar()[1]
    else:
        return int(date.strftime('%U'))


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]'