我想根据这个系统从时间戳中获取工作周数:
美国,加拿大,大部分拉丁美洲,日本,以色列,韩国等都使用一周编号系统(在我们的计算器中称为北美),其中任何给定年份的第一周(编号1)是包含的一周1月1日。一周的第一天是星期日,星期六是最后一天。
https://www.calendar-12.com/week_number
Python的strftime方法支持%U
和%W
,但这些都不匹配该系统。 Pandas还根据ISO 8601添加了%V
,但这也不是北美使用的。
好的,这就是我提出的......如果将它包含在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)
以下是我在其中一个项目中使用的代码。它基于北美周编号系统,其中第一周是包含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)