Python 从日期时间算起的北美工作周数?

Python North American work week number from datetime?

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

USA, Canada, most of Latin America, Japan, Israel, South Korea, among others, use a week numbering system (called North American in our Calculator) in which the first week (numbered 1) of any given year is the week which contains January 1st. The first day of a week is Sunday and Saturday is the last.

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

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

好的,这就是我的想法...如果它包含在日期时间或 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)

以下是我在我的一个项目中使用的代码。它基于北美周编号系统,其中第一周是包含 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)