How can I get the current week using Python?

前端 未结 7 1560
夕颜
夕颜 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:04

    How do you identify weeks? Here I'm identifying by a day in that week, using a function which gets the Sunday in that week (what you used in your example), and then returns it plus the next 6 days.

    import datetime
    
    one_day = datetime.timedelta(days=1)
    
    def get_week(date):
      """Return the full week (Sunday first) of the week containing the given date.
    
      'date' may be a datetime or date instance (the same type is returned).
      """
      day_idx = (date.weekday() + 1) % 7  # turn sunday into 0, monday into 1, etc.
      sunday = date - datetime.timedelta(days=day_idx)
      date = sunday
      for n in xrange(7):
        yield date
        date += one_day
    
    print list(get_week(datetime.datetime.now().date()))
    # [datetime.date(2010, 1, 3), datetime.date(2010, 1, 4),
    #  datetime.date(2010, 1, 5), datetime.date(2010, 1, 6),
    #  datetime.date(2010, 1, 7), datetime.date(2010, 1, 8),
    #  datetime.date(2010, 1, 9)]
    print [d.isoformat() for d in get_week(datetime.datetime.now().date())]
    # ['2010-01-03', '2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07',
    #  '2010-01-08', '2010-01-09']
    

提交回复
热议问题