简体   繁体   English

Python:在isocalendar或strftime中定义星期定义的开始日期

[英]Python: Define starting day in week definition in isocalendar or strftime or else

I need to partition pandas.tslib.Timestamp into weeks. 我需要将pandas.tslib.Timestamp分区为几周。 So, given that a is a pd.DataFrame I used 所以,假设a是我使用的pd.DataFrame

tmp = pd.to_datetime(a) 
tmp = tmp.apply(lambda x: str(str(x.isocalendar()[1]))

The problem is that my week starts not on Monday or Sunday but Tuesday (it can even start on Wed - it is user defined). 问题是我的周开始不是周一或周日而是周二(它甚至可以从周三开始 - 它是用户定义的)。 Is it possible to change the starting week definition and still to use generic python functions? 是否可以更改起始周定义并仍然使用通用python函数?

Or is there another work-around? 或者还有另一种解决方法吗?

Use an offset; 使用偏移量; you can re-cast the weekday value to any other in the range, then subtract from the week number: 您可以将工作日值重新投射到范围内的任何其他值,然后从周数中减去

user_sow = 3  # wednesday (monday is 1, sunday is 7)

tmp.apply(lambda x: x.isocalendar()[1] - (x.isoweekday() < user_sow))

This subtracts 1 (boolean True is equal to 1 in integer contexts) from the week number if the weekday is before the start of the user-configured week. 如果工作日在用户配置的周开始之前,则从周数中减去1(布尔值True在整数上下文中等于1)。

Demo: 演示:

>>> dt = date.today()   # today's a Wednesday
>>> dt
datetime.date(2015, 4, 28)
>>> dt.isocalendar()[1]
18
>>> dt.isocalendar()[1] - (dt.isoweekday() < 2)  # week starts on Tuesday
18
>>> dt.isocalendar()[1] - (dt.isoweekday() < 3)  # week starts on Wednesday
17

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

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