如何用Python找出今年6月16日(wk24)的周数?


当前回答

userInput = input ("Please enter project deadline date (dd/mm/yyyy/): ")

import datetime

currentDate = datetime.datetime.today()

testVar = datetime.datetime.strptime(userInput ,"%d/%b/%Y").date()

remainDays = testVar - currentDate.date()

remainWeeks = (remainDays.days / 7.0) + 1


print ("Please pay attention for deadline of project X in days and weeks are  : " ,(remainDays) , "and" ,(remainWeeks) , "Weeks ,\nSo  hurryup.............!!!") 

其他回答

一般要获取当前周数(从周日开始):

from datetime import *
today = datetime.today()
print today.strftime("%U")

已经给出了很多答案,但我想补充一下。

如果您需要将周显示为年/周样式(例如,1953 - 2019年第53周,2001 - 2020年第1周等),您可以这样做:

import datetime

year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)

它将使用当前的年份和周,写这篇文章当天的long_week_num将是:

>>> 2006

别人建议的ISO周是很好的,但可能不适合你的需求。它假设每周从星期一开始,这导致了年初和年底的一些有趣的异常情况。

如果你宁愿使用一个定义,说第一周总是1月1日到1月7日,而不管星期几,可以使用这样的推导:

>>> testdate=datetime.datetime(2010,6,16)
>>> print(((testdate - datetime.datetime(testdate.year,1,1)).days // 7) + 1)
24

如果你只使用等历法周数,那么以下内容就足够了:

import datetime
week = date(year=2014, month=1, day=1).isocalendar()[1]

这将检索由iscalendar为周数返回的元组的第二个成员。

但是,如果您打算使用处理公历的日期函数,那么单独使用iscalendar是行不通的!举个例子:

import datetime
date = datetime.datetime.strptime("2014-1-1", "%Y-%W-%w")
week = date.isocalendar()[1]

这里的字符串表示返回2014年第一周的星期一作为日期。当我们使用iscalendar在这里检索周数时,我们希望得到相同的周数,但我们没有。相反,我们得到的周数是2。为什么?

公历的第一周是包含星期一的第一周。等日历中的第1周是包含星期四的第一周。2014年初的部分周包含一个星期四,所以这是等历的第一周,日期是第2周。

如果我们想要得到公历周,我们将需要从等历法转换为公历。下面是一个简单的函数。

import datetime

def gregorian_week(date):
    # The isocalendar week for this date
    iso_week = date.isocalendar()[1]

    # The baseline Gregorian date for the beginning of our date's year
    base_greg = datetime.datetime.strptime('%d-1-1' % date.year, "%Y-%W-%w")

    # If the isocalendar week for this date is not 1, we need to 
    # decrement the iso_week by 1 to get the Gregorian week number
    return iso_week if base_greg.isocalendar()[1] == 1 else iso_week - 1

对于pandas用户,如果你想获得一列周数:

df['weekofyear'] = df['Date'].dt.week