简体   繁体   中英

Python North American work week number from datetime?

I am trying to get the work week number from a timestamp according to this system:

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's strftime method supports %U and %W , but neither of these match that system. Pandas also adds %V following ISO 8601 but this is not what is used in North America either.

Ok here's what I came up with... it would be nice if this was included in datetime or Pandas though

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)

The following is the code I used in one of my projects. It is based on North American week numbering system where the first week is the week that contains January 1st.

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

For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM