如何在Python中获取给定年份和日历周的所有日期?

时间:2019-04-30 22:09:57

标签: python datetime calendar

假设您有一个“ 2017”年和一个等距周“ 13”。您如何有效地(使用日期时间或日历之类的库)将与今年和日历周相对应的所有日期作为Python列表?

2 个答案:

答案 0 :(得分:1)

不确定这是您想要的。我玩过calendar模块,这是我设法做到的最好,让我知道:

import calendar

def get_week(y, w):
    weeks  = [
        tuple(w) 
        for t in cal.yeardatescalendar(y) for month in t for w in month
        if w[0].year == y
    ]
    weeks = sorted(list(set(weeks)))
    return list(weeks[w-1])
get_week(2017, 13)

输出:

[datetime.date(2017, 3, 27),
 datetime.date(2017, 3, 28),
 datetime.date(2017, 3, 29),
 datetime.date(2017, 3, 30),
 datetime.date(2017, 3, 31),
 datetime.date(2017, 4, 1),
 datetime.date(2017, 4, 2)]

或使用datetime.isocalendar()函数:

import datetime as dt

def get_week(y, w):
    first = next(
        (dt.date(y, 1, 1) + dt.timedelta(days=i) 
         for i in range(367)
         if (dt.date(y, 1, 1) + dt.timedelta(days=i)).isocalendar()[1] == w))
    return [first + dt.timedelta(days=i) for i in range(7)]

get_week(2017, 13)

答案 1 :(得分:0)

这应该做到的。

import datetime
def get_month (year: int, weekday: int):
    start = datetime.datetime (year=year, month=1, day=1)
    '''
    Weekday correction:
    source: https://www.calendar-week.org/
    "In Europe, the first calendar week of the year is the week that
    contains four days of the new year."
    '''
    if start.weekday () >= 4:
        start += datetime.timedelta (days=7-start.weekday ())
    else:
        start -= datetime.timedelta (days=start.weekday ())
    start += datetime.timedelta (days=7*(weekday-1))
    return [start + datetime.timedelta(days=i) for i in range (0, 7)]

将返回datetime-s的列表。要获取字符串表示形式:

print (list (map (lambda x: str (x.date()), get_month (2017, 2))))