1

我正在尝试获取给定一周内的天数列表。我可以得到年份和星期。

例如:

>>> year, week, dow = datetime.today().isocalendar()
>>> week
>>> 39

我想得到第 39 周的 7 天。今年,2015 年,我会得到

[21, 22, 23, 24, 25, 26, 27]

如此处所示

笔记

我发现了很多问题:

这不是重复的,我不需要过去 7 天,而且我已经有了当前的周数。

我需要在给定的一周内获得 7 天,在这种情况下是第 39 周。感谢您的宝贵时间。

4

3 回答 3

1

的困难isocalendar在于它并没有真正计算每月的日期。因此,您必须翻译回去才能得到它。strptime可以帮忙:

year, week, dow = datetime.today().isocalendar()
result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]

我们在这里所做的是构建一个striptime可以理解的字符串,从一周前开始(考虑从 0 到 1 计数)并从一周开始(星期一,即1)开始,并为每一天构建一个日期时间前进7天。

通过week在这两个语句之间进行操作(添加或删除几周以达到月休),我们可以看到它有效:

>>> year, week, dow = datetime.today().isocalendar()
>>> result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]
>>> result
[21, 22, 23, 24, 25, 26]
>>> year, week, dow = datetime.today().isocalendar()
>>> week = week + 1
>>> result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]
>>> result
[28, 29, 30, 1, 2, 3]

现在,为了解决评论中提出的两个非常现实的问题,我们必须稍微修改一下:

year, week, dow = datetime.today().isocalendar()
week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
result = [(week_start + timedelta(days=x)).day for x in range(0,7)]

这用于timedelta增加。为了完成这项工作,我们必须跨周间隔进行备份(因此使用-2代替-1)。然后,当我们迭代一周时,for 理解增加了一个越来越大的时间增量:

>>> year, week, dow = datetime.today().isocalendar()
>>> week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
>>> result = [(week_start + timedelta(days=x)).day for x in range(0,7)]
>>> result
[20, 21, 22, 23, 24, 25, 26]
>>> year, week, dow = datetime.today().isocalendar()
>>> week = week + 1
>>> week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
>>> result = [(week_start + timedelta(days=x)).day for x in range(0,7)]
>>> result
[27, 28, 29, 30, 1, 2, 3]
于 2015-09-21T23:21:03.527 回答
1

当然可以改进,但似乎可行....

def days_of_the_current_numbered_week():

    import datetime
    import  calendar

     # dictionary of days of the week
    days = {   0 :  "Sunday",
            1 : "Monday",
            2 : "Tuesday",
            3 : "Wednesday",
            4 : "Thursday",
            5 : "Friday",
            6 : "Saturday",
            7 : "Sunday" }


    allYearDates = []
    w_days_numbers = []

    # today
    now = datetime.datetime.now()

    # get current values for year, mon, day
    year = int(now.year)
    mon = int(now.month)
    day = int(now.day)

    # get this week number
    # thisWeekN = datetime.date(year, mon, day).isocalendar()[1]

    thisWeekN = datetime.datetime.utcnow().isocalendar()[1]

    # get Calendar obect
    c = calendar.Calendar()

    # get all the days for this year in a list
    for i in range(1, 13):
        for d in c.itermonthdays2(year, i):
            allYearDates.append(d)
    # in the first seven days could be 0's as days, to continue week #'s
    # these tuples need to be removed to produce accurate mapping between
    # weeks and 7 days chunks
    first_seven = allYearDates[:7]
    no_zeros =  [ d for d in first_seven if  d[0] != 0]

    allYearDates = no_zeros + allYearDates[8:]
    # divid all days of year list into one week chuncks
    lt7 = listChunks(allYearDates,7)

    # get days for this week number
    thisWeekDays = lt7[thisWeekN]

    # remove right part of the days tuple
    sevenDaysL = [x for x,y in  thisWeekDays]

    # get week day numbers  1-7 for this week
    for d in sevenDaysL:
        w_days_numbers.append(datetime.date(year, mon, d).isocalendar()[2])

    # zip week day numbers with the dates
    zl = zip(sevenDaysL, w_days_numbers)

    # month number prefix
    if thisWeekN == 1:
        prefix = 'st'
    elif thisWeekN == 2:
        prefix = 'nd'
    elif thisWeekN == 3:
        prefix = 'rd'
    else:
        prefix= "th"

    # print heading
    print("\n 7 days of this {}{} week: of the year {}"
          .format(thisWeekN,prefix, year))
    print("-------------------------------------------")

    # print results
    for el in  list(zl):
        if el[0] == day:
            print("* {} *  {}".format(el[0],days[el[1]]))
        else:
            print("  {}    {}".format(el[0],days[el[1]]))

    mytime= datetime.datetime.now().strftime("%Y-%m-%d %H-%M")
    print("================")
    print(mytime)

days_of_the_current_numbered_week()

输出

第 39 周的 7 天:2015 年

17 星期四

18 星期五

19 星期六

20 星期日

21 星期一

22 星期二

23 星期三

于 2015-09-22T02:05:28.097 回答
0

首先,找到一年的开始日期。这在互联网上很容易找到。这为您提供了一年中第 1 周的偏移量。

请注意,星期将让您计算一年中的哪一天,范围为 1-365。第 01 周从第 1 天开始;第 02 周从第 8 天开始,以此类推。

start_day = 1 + (week-1) * 7 - 偏移量

首先,找到一年的开始日期。这在互联网上很容易找到。这为您提供了一年中第 1 周的偏移量。

既然您有了开始日期,您就可以轻松找到月份中的哪一天。在进入给定月份的范围之前减去每个月的天数有点繁琐,但这很简单。

这能让你前进吗?我已经用英文描述做了这个,因为你没有给我们任何调试代码。

于 2015-09-21T23:00:56.567 回答