How can I get the current week using Python?

前端 未结 7 1531
夕颜
夕颜 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']
    
    0 讨论(0)
  • 2020-12-15 23:04
    current_week = datetime.datetime.now().isocalendar()[1]
    
    0 讨论(0)
  • 2020-12-15 23:06

    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']
    }
    
    0 讨论(0)
  • 2020-12-15 23:08

    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 
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 23:10

    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.

    0 讨论(0)
提交回复
热议问题