Python North American work week number from datetime?

爱⌒轻易说出口 提交于 2019-12-08 04:05:29

问题


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.


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/55658435/python-north-american-work-week-number-from-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!