简体   繁体   English

从python datetime中提取星期并获取序列号?

[英]Extracting the week from python datetime and getting the serial number?

I have a dataframe with column name order date containing date from July 2014 to June 2015 in the format 2014-10-17 15:11:54. 我有一个数据列,其列名订购日期包含2014年7月至2015年6月的日期,格式为2014-10-17 15:11:54。 Using datetime I have extracted the week number from the date. 我使用datetime从日期中提取了星期数。 However I get the starting week as 27 for July 2014 than for January 2015 starts again as week 1. What I want is July 2014 as week 1 continue till June 2015 and ends as 53. 但是,我将2014年7月的起始周定为27,而将2015年1月的起始周定为第1周。我想要的是2014年7月,因为第1周持续到2015年6月,结束时是53。

df['Week'] = df.order_date.dt.week 

Use the above code to get the week number after that to get as 1 for July 2014 use 使用上面的代码获取之后的星期数,以获取2014年7月使用的第1周

def time_period(x):
    if df.Week >= 26:
        return df.Week -25
    else:
        return df.Week +28
df['week_serial'] = df.Week.apply(lambda x: time_period(x))

This gives an error- The truth value of a Series is ambiguous. 这给出了一个错误-系列的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all(). 使用a.empty,a.bool(),a.item(),a.any()或a.all()。

Well since df.Week already contains the week number, the function should look like: 好吧,由于df.Week已包含星期数,因此该函数应如下所示:

def time_period(x):
    if x >= 26:
        return x-25
    else:
        return x+28

But I think you here basically are looking for a modulo operation: 但是我认为您基本上是在寻找模运算:

df['week_serial'] = (df['Week'] + 27) % 53 + 1

This will map 26 on 1 , 27 on 2 , etc.; 这将在1上映射26 ,在2上映射2727类推; and 25 on 53 and 24 on 52 , etc. 以及53上的2552上的24等。

So for sample input: 因此,对于示例输入:

>>> df
   Week
0    13
1    49
2    47
3    12
4    35
5    17
6     1
7    46
8    19
9     0

we obtain: 我们获得:

>>> (df['Week'] + 27) % 53 + 1
0    41
1    24
2    22
3    40
4    10
5    45
6    29
7    21
8    47
9    28
Name: Week, dtype: int64

Given that you already have datetime.datetime objects, it is probably the easiest to use those. 鉴于您已经具有datetime.datetime对象,使用它们可能是最简单的。

First, define your start date. 首先,定义您的开始日期。

In [1]: import datetime

In [2]: start  = datetime.datetime(2014, 7, 1)
Out[2]: datetime.datetime(2014, 7, 1, 0, 0)

Then determine the timedelta between each date and the start, and convert that to days and then weeks. 然后确定每个日期和开始之间的时间timedelta ,并将其转换为几天然后几周。

In [3]: (datetime.datetime(2015, 3, 24) - start).days
Out[3]: 266

In [4]: (datetime.datetime(2015, 3, 24) - start).days // 7 + 1
Out[4]: 39

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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