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


当前回答

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

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

其他回答

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

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

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

这是另一个选择:

import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime(d, '%U'))

结果是24。

见:http://docs.python.org/library/datetime.html strftime-and-strptime-behavior

我发现这是获得周数的最快方法;所有的变体。

from datetime import datetime


dt = datetime(2021, 1, 3)  # Date is January 3rd 2021 (Sunday), year starts with Friday

dt.strftime("%W")  # '00'; Monday is considered first day of week, Sunday is the last day of the week which started in the previous year
dt.strftime("%U")  # '01'; Sunday is considered first day of week
dt.strftime("%V")  # '53'; ISO week number; result is '53' since there is no Thursday in this year's part of the week

%V的进一步说明可以在Python文档中找到:

国际标准化组织的一年包括52或53个完整的星期,其中一周从星期一开始,到星期日结束。ISO年的第一周是包含星期四的一年的第一个(公历)周。这被称为第1周,星期四的ISO年份与公历年份相同。

https://docs.python.org/3/library/datetime.html#datetime.date.isocalendar

注意:请记住返回值是一个字符串,因此如果需要一个数字,则将结果传递给int构造函数。

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

如果您需要将周显示为年/周样式(例如,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
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.............!!!")