Python Week Numbers,其中所有周都有 7 天,无论年份是否翻转

标签 python mysql date

我有一个应用程序,我需要测量一年中的周数,我希望所有的星期都有 7 天,无论这些天数是否在不同的年份。

例如,我希望从 2012 年 12 月 30 日到 2013 年 1 月 5 日的所有日子都在同一周内。

但这在 Python 中并不是直接可以做到的,因为正如 datetime 文档所述 here :

%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.

我不希望将“第一个星期日之前的新年中的所有日子”视为第 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

即使这两天是星期一和星期二,但尊重地应该在同一周内,当一周被认为是从星期日开始到星期六结束时。

相反,我想要的功能可以反射(reflect) MySQL 在模式 2 中对 yearweek 所做的操作(文档 here)。

例如,

 mysql> select yearweek('2013-01-01', 2) as week;
 +--------+                                      
 | week   |                                      
 +--------+                                      
 | 201253 |                                      
 +--------+                                      
 1 row in set (0.64 sec)                         

请注意,即使日期是 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          

最佳答案

isoweek 模块提供了您需要的一切。

来自文档:

from isoweek import Week
w = Week(2011, 20)
print "Week %s starts on %s" % (w, w.monday())

print "Current week number is", Week.thisweek().week
print "Next week is", Week.thisweek() + 1

http://pypi.python.org/pypi/isoweek/1.1.0

关于Python Week Numbers,其中所有周都有 7 天,无论年份是否翻转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272920/

相关文章:

MySQL 时间戳到 Excel 日期/时间

mysql - 选择字段的不同子字符串值并计算该选择中字符的实例数

python - 如何将 jupyter 内核从 Python 2 更改为 python 3?

python - Django:模型对象保存中的 datetime.now() 时间不一致

python - 通过 python 运行 selenium 时不是有效的选择器错误

python - 如何检查 Python 中的函数类型?

PHP - mySQL 查询传递结果作为 session 变量不起作用

python - 在波兰语中用月份名称格式化日期,在 python 中

c++ - 两个日期之间有多少天 C++

如果手动输入日期,SQL 日期差异会返回错误结果