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


当前回答

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

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

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

其他回答

iscalendar()对于某些日期返回错误的年和周数值:

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1

与Mark Ransom的方法相比:

>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52

这是另一个选择:

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

您可以直接从datetime作为字符串获取周数。

>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'

你也可以得到不同的“类型”的周数的年份改变strftime参数:

%U - Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53 %W - Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53 [...] (Added in Python 3.6, backported to some distribution's Python 2.7's) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the strftime() method. [...] %V - ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53 from: datetime — Basic date and time types — Python 3.7.3 documentation

我是从这里知道的。它在Python 2.7.6中对我有效

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.............!!!") 

对于一年中的瞬时周的整数值,尝试:

import datetime
datetime.datetime.utcnow().isocalendar()[1]