从日期时间开始的Python北美工作周编号? [英] Python North American work week number from datetime?
问题描述
我正在尝试根据此系统从时间戳获取工作周编号:
I am trying to get the work week number from a timestamp according to this system:
美国,加拿大,拉丁美洲大部分地区,日本,以色列,韩国以及其他
,使用周编号系统(在我们的
计算器中称为北美),其中任意一年的第一周(编号为1)为
包含1月1日的一周。一周的第一天是星期日
,星期六是最后一天。
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
,但是这两个都不匹配该系统。熊猫还在ISO 8601之后添加了%V
,但这在北美也不是。
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.
推荐答案
好吧,这是我想出的...不过,如果将它包含在datetime或Pandas中,那就太好了
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)
这篇关于从日期时间开始的Python北美工作周编号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!