【问题标题】:Python North American work week number from datetime?日期时间的Python北美工作周数?
【发布时间】:2019-04-12 19:39:06
【问题描述】:

我正在尝试根据此系统从时间戳中获取工作周数:

美国、加拿大、拉丁美洲大部分地区、日本、以色列、韩国等 其他人,使用周编号系统(在我们的 计算器),其中任何给定年份的第一周(编号为 1)是 包含 1 月 1 日的那一周。一周的第一天是星期日 星期六是最后一个。

https://www.calendar-12.com/week_number

Python 的 strftime 方法支持 %U%W,但它们都不匹配该系统。 Pandas 还在 ISO 8601 之后添加了%V,但这也不是在北美使用的。

【问题讨论】:

  • 您能解释一下给定选项为何不适合您吗?它们有何不同?
  • 另外,看看这个类似的问题stackoverflow.com/q/2600775/9225671
  • @Ralf 该问题根据 ISO 8601 询问并回答了周数,正如我在问题中提到的那样,这不是北美的标准。至于内置的 Python 选项有何不同,您可以在此处阅读它们的描述:strftime.org。它们只是与我的问题中的描述不符。我都试过了,比较了,这里有一个例子(2016/01/02应该是WW01):screencast.com/t/5lSOb7NRmsG
  • 所以基本上你想要实现的是 %U 选项返回的值,但递增 1(因此年份从 1 而不是 0 开始),对吗?
  • @Ralf 我试过了,但仍然不正确。第一步是递增 1,但你仍然有这个问题:screencast.com/t/5r4jttvh(这些都应该是同一周)。所以我必须用 1 替换 53。然后我发现有些年份的最后一周是 54,所以我不得不在前一年的最大值上进行替换。即使我发现%U 在 2017 年等年份从 1 开始,所以最初递增 1 会使整年错...

标签: python datetime timestamp week-number


【解决方案1】:

以下是我在一个项目中使用的代码。它基于北美周编号系统,其中第一周是包含 1 月 1 日的那一周。

from datetime import date

def week1_start_ordinal(year):
    jan1 = date(year, 1, 1)
    jan1_ordinal = jan1.toordinal()
    jan1_weekday = jan1.weekday()
    week1_start_ordinal = jan1_ordinal - ((jan1_weekday + 1) % 7)
    return week1_start_ordinal

def week_from_date(date_object):
    date_ordinal = date_object.toordinal()
    year = date_object.year
    week = ((date_ordinal - week1_start_ordinal(year)) // 7) + 1
    if week >= 52:
        if date_ordinal >= week1_start_ordinal(year + 1):
            year += 1
            week = 1
    return year, week

例如:

>>> from datetime import date
>>> week_from_date(date(2015, 12, 27))
(2016, 1)

【讨论】:

    【解决方案2】:

    好的,这就是我想出的......如果它包含在 datetime 或 Pandas 中会很好

    def US_week(ts):
        if pd.isnull(ts):
            return np.nan
    
        import datetime as dt
        U = int(ts.strftime('%U'))
    
    
        # If this is last week of year and next year starts with week 0, make this part of the next years first week
        if U == int(dt.datetime(ts.year, 12, 31).strftime('%U')) and int(
                dt.datetime(ts.year + 1, 1, 1).strftime('%U')) == 0:
            week = 1
    
        # Some years start with 1 not 0 (for example 2017), then U corresponds to the North American work week already
        elif int(dt.datetime(ts.year, 1, 1).strftime('%U')) == 1:
            week = U
        else:
            week = U + 1
    
        return week
    
    def US_week_str(ts):
        week = US_week_str(ts)
        return "{}-{:02}".format(ts.year, week)
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 2011-01-14
      相关资源
      最近更新 更多