How can I get the current week using Python?

前端 未结 7 1536
夕颜
夕颜 2020-12-15 22:57

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\         


        
7条回答
  •  独厮守ぢ
    2020-12-15 23:08

    If you're OK with the ISO standard:

    >>> import collections
    >>> dd = collections.defaultdict(list)
    >>> jan1 = datetime.date(2010, 1, 1)
    >>> oneday = datetime.timedelta(days=1)
    >>> allyear = [jan1 + k*oneday for k in range(365 + 6)]
    >>> for d in allyear:
    ...   y, w, wd = d.isocalendar()
    ...   if y == 2010: dd[w].append(d.strftime('%m/%d/%Y'))
    ... 
    

    This produces slightly different results than the ones you're looking for (by ISO standard, weeks begin on Monday, not Sunday...), e.g.:

    >>> dd[1]
    ['01/04/2010', '01/05/2010', '01/06/2010', '01/07/01/2010', '01/08/2010', '01/09/2010', '01/10/2010']
    

    but you could tweak this by simulating an appropriate "off by one" error!-)

    The calendar modules let you set any weekday as "first day of week", but offers no simple way to get all weeks (without duplications when a week is split between two months), so I think that working directly off datetime is probably a better idea.

提交回复
热议问题