如何用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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录