我有一个应用程序,我需要测量一年中的周数,并且我希望所有周数都有7天,无论日期是否在不同年份.
例如,我希望从2012年12月30日到2013年1月5日的所有日子都在同一周.
但这不是直线前进的蟒蛇做,因为随着datetime文档指出这里:
%U Week number of the year (Sunday as the first day of the week)
as a decimal number [00,53]. All days in a new year preceding the
first Sunday are considered to be in week 0.
Run Code Online (Sandbox Code Playgroud)
我不希望"在第一个星期天之前的新年中的所有日子"被认为是在第0周.第0周将不到7天,2012年的最后一周也是如此.
因此Python返回:
import datetime
datetime.date(2012, 12, 31).strftime('%Y-%U')
>>> 2012-53
import datetime
datetime.date(2013, 01, 01).strftime('%Y-%U')
>>> 2013-00
Run Code Online (Sandbox Code Playgroud)
即使这两天是星期一和星期二,也应该是在同一周,即一周被认为是星期日开始,星期六结束.
相反,我想要的功能可以反映MySQL yearweek在模式2中的作用(这里是 doc ).
例如,
mysql> select yearweek('2013-01-01', 2) as week;
+--------+
| week |
+--------+
| 201253 |
+--------+
1 row in set (0.64 sec)
Run Code Online (Sandbox Code Playgroud)
请注意,即使日期是2013年,本周也被视为201253,保证2012年的最后一周为7天.
这已经在Python中实现了吗?
下面的日历供参考:
December 2012
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
January 2013
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Run Code Online (Sandbox Code Playgroud)
我没有找到执行此操作的本机方法,因此我只是编写了一些非常简单的代码来测试该周是否是第零周,这意味着该日期在当年但在第一个完整的开始日期之前当年的第几周,相当于上一年的最后一周。
def get_week(date):
date = datetime.datetime.strptime(date, '%Y-%m-%d')
week = date.strftime('%Y%U')
if week[-2:] == '00':
year = week[:-2]
prev_year = int(year) - 1
week = datetime.date(prev_year, 12, 31).strftime('%Y%U')
else:
pass
return week
Run Code Online (Sandbox Code Playgroud)