首页 文章

Python周数,所有周都有7天,无论年度翻转

提问于
浏览
5

我有一个应用程序,我需要测量一年中的周数,并且我希望所有周数都有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

即使这两天是星期一和星期二,也应该是在同一周,即一周被认为是星期日开始,星期六结束 .

相反,我想要的功能可以反映MySQL在模式2(doc here)中使用 yearweek 所做的事情 .

例如,

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

3 回答

  • -3

    我想问一下为什么你需要有自己的周处理逻辑 . 根本原因是什么?

    回到问题所在 . 如何使用自己的代码处理逻辑:yu = datetime.date(2013,1,1).strftime(“%Y-%U”) . split(“ - ”)if(int(yu [1])= = 0):week =(datetime.date(2012,12,31).strftime(“%Y-%U”) . split(' - '))[1]

  • 1

    我没有找到本地方法来做这个,所以我只写了一些非常简单的代码来测试一周是否是第零周,这意味着日期是在当前年份但在第一次完整的开始日期之前当年的一周,相当于该日期是上一年的最后一周 .

    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
    
  • 0

    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

相关问题