从日期时间开始的Python北美工作周编号?

时间:2019-04-12 19:39:06

标签: python datetime timestamp week-number

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

  

美国,加拿大,大部分拉丁美洲,日本,以色列,韩国,   其他人,则使用星期编号系统(在我们的系统中称为“北美”   计算器)其中任何给定年份的第一周(编号1)为   包含1月1日的一周。一周的第一天是星期日   而星期六是最后一个。

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

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

2 个答案:

答案 0 :(得分:1)

以下是我在一个项目中使用的代码。它基于北美星期编号系统,其中第一周是包含1月1日的那一周。

$ cat t7.py
import cupy as cp #Importing CuPy

#Defining the CUDA kernel
multiply = cp.RawKernel(r'''
extern "C" __global__
void multiply(const int* p, const int* q, int* z) {
    int tid = blockDim.x * blockIdx.x + threadIdx.x;
    z[tid] = p[tid] + q[tid];
 }
''', 'multiply')

#First two arrays are set as 0,1,2,3....upto 300
p = cp.arange(30, dtype=cp.int32).reshape(6,5)
q = cp.arange(30, dtype=cp.int32).reshape(6,5)

#Setting a new array with zeros to pass to kernel for computation
z = cp.zeros((6,5), dtype=cp.int32)
#Invoking the kernel with a grid of 250 blocks, each consisting of 1024 threads
multiply((6, ), (5, ), (p, q, z))  # grid, block and arguments

#Displaying the output computed on the kernel
print(z)
$ python t7.py
[[ 0  2  4  6  8]
 [10 12 14 16 18]
 [20 22 24 26 28]
 [30 32 34 36 38]
 [40 42 44 46 48]
 [50 52 54 56 58]]
$

例如:

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

答案 1 :(得分:0)

好的,这就是我的想法。。。如果它包含在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)