代码之家  ›  专栏  ›  技术社区  ›  Rikkas

python中当前月份的日历周列表

  •  2
  • Rikkas  · 技术社区  · 8 年前

    我想知道本月的几周。我可以得到当月的周数(当前值),但我需要以正确的顺序得到一个列表。例如,七月 w = [27, 28, 29, 30] 因为本周是本月4周中的第三周。有人能帮我吗?

    import datetime
    
    kw = datetime.datetime.today().isocalendar()[1]
    weeks = [7,14,21,28]
        for idx, i in enumerate(weeks):
            delta = datetime.timedelta(days=i)
            if (a - delta).month != a.month:
                current_w = idx
    
    2 回复  |  直到 8 年前
        1
  •  4
  •   Bernhard    8 年前

    你可以用 datetime 把第一周和最后一周都弄到手,然后把这两周之间的一切都弄到手。

    import datetime
    import calendar
    
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    first_week = datetime.datetime(year, month, calendar.monthrange(year, month)[0]).isocalendar()[1]
    last_week = datetime.datetime(year, month, calendar.monthrange(year, month)[1]).isocalendar()[1]
    
    print(list(range(first_week, last_week + 1)))
    

    from datetime import datetime 会救你所有的 datetime.datetime 使用btw。

        2
  •  1
  •   Serge Ballesta    8 年前

    如果您只希望一个月内包含的周数,则第一周将是包含该月第7周的周数。最后一周将是下个月1号的前一周。

    这足以提供以下功能:

    def weeks_in_month(month, year=None):
        """Returns the (ISO) weeks fully contained in a month.
    month is an integer between 1 and 12. Year is the current year
    if not given"""
        if year is None:
            year = datetime.date.today().year
        first = datetime.date(year, month, 7).isocalendar()[1]
        nextd = datetime.date(year + 1, 1, 1) if month == 12 \
            else datetime.date(year, month + 1, 1)
        nextw = nextd.isocalendar()[1]
        return list(range(first, nextw))