【问题标题】:Equivalent of Excel's Weeknum function in PythonPython中Excel Weeknum函数的等价物
【发布时间】:2018-07-19 10:03:30
【问题描述】:

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

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

有人可以帮忙吗?

【问题讨论】:

标签: excel python-3.x excel-formula python-datetime


【解决方案1】:

这是伪代码。你可以把它变成Python。 您将定义一个函数 Weeknum,它将日期 d 作为其输入并返回一个介于 1 和 53 之间的数字。 您将使用 weekday 函数来确定第一周短了多少天。因此,如果 1 月 1 日是一周的第一天,则短天数为 0。如果 1 月 1 日是一周的最后一天,则短天数为 6。有几种方法可以做到这一点,具体取决于一点关于一周的第一天如何映射到工作日功能的约定。在最坏的情况下,您可以通过将计数器设置为 1 并将日期变量设置为一年中的 1 月 1 日来计算第一周的天数,而日期的日期不是一周的最后一天,而是一个计数器和日期。那么短的天数是 7 减去计数器。 获取 1 到 366 之间的数字 j,表示 d 年的某天。一种方法是取 d 和 d 年 1 月 1 日之间的天数差 1+。 然后 Weeknum 应该返回 (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

【讨论】:

  • 你打赌。我觉得有一些一两行解决方案可以利用现有功能,并在它们不同意您期望的行为时进行纠正,但这很有趣。
猜你喜欢
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 2014-04-20
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
相关资源
最近更新 更多