Excel 的 Weeknum 函数在 Python 中的等价物

Equivalent of Excel's Weeknum function in Python

我正在研究自动化目前在 Excel 中处理的报告。作为其中的一部分,我想要一个 Python 等同于 Excel 的 Weeknum 函数(使用系统 1。Reference here ),它将 1 月 1 日的那一周视为第 1 周。

PS:我已经尝试过 ISOCalendar,但它给出了错误的星期,因为它的星期从星期一开始。我也尝试了 strftime("%U") 并且它 returns 相同的错误数字。

有人可以帮忙吗?

这是伪代码。你可以把它变成Python。 您将定义一个函数 Weeknum,它将日期 d 作为其输入,returns 是 1 到 53 之间的一个数字。 您将使用 weekday 函数来确定第一周有多少天是短的。因此,如果 1 月 1 日是一周的第一天,则剩余天数为 0。如果 1 月 1 日是一周的最后一天,则剩余天数为 6。有几种方法可以做到这一点,具体取决于关于一周的第一天如何很好地映射到工作日函数的约定。最坏的情况下,您可以通过将计数器设置为 1 并将日期变量设置为当年的 1 月 1 日来计算第一周的天数,而日期不是一周的最后一天,而是将一个计数器设置为日期。那么空头天数就是 7 减去计数器。 获取 1 到 366 之间的第 j 个数字,代表 d 年的第几天。一种方法是将 d 与 d 年的 1 月 1 日之间的天数相差 1+。 那么Weeknum应该return(j+6+短天数)div 7.

编辑:我在 Python

中写了它
import datetime
def julian(d):#takes a date d and returns what day in the year it is 1..366
    jan1 = datetime.date(d.year,1,1)
    return 1+(d-jan1).days
def daysInFirstWeekOfJanuary(y):
    #takes a year and says how many days there were in the first week of #january that year
    janDay = datetime.date(y,1,1)
    result = 1
    while (janDay.weekday()!=5):#until Saturday, change if you hold Sunday is not the first day of the week
        result=result+1
        janDay=janDay+datetime.timedelta(days=1)
    return result
def daysShortInFirstWeekOfJanuary(y):
    return 7-daysInFirstWeekOfJanuary(y)
def weeknum(d):#takes a date and returns the week number in the year
#where Jan 1 of the year is the start of week 1, and the following Sunday starts week 2
     return(julian(d)+6+daysShortInFirstWeekOfJanuary(d.year)) // 7