如何用Python找出今年6月16日(wk24)的周数?
当前回答
我们也有类似的问题,于是我们想出了这个逻辑 我已经测试了1年的测试用例,并且全部通过
import datetime
def week_of_month(dt):
first_day = dt.replace(day=1)
dom = dt.day
if first_day.weekday() == 6:
adjusted_dom = dom
else:
adjusted_dom = dom + first_day.weekday()
if adjusted_dom % 7 == 0 and first_day.weekday() != 6:
value = adjusted_dom / 7.0 + 1
elif first_day.weekday() == 6 and adjusted_dom % 7 == 0 and adjusted_dom == 7:
value = 1
else:
value = int(ceil(adjusted_dom / 7.0))
return int(value)
year = 2020
month = 01
date = 01
date_value = datetime.datetime(year, month, date).date()
no = week_of_month(date_value)
其他回答
datetime。Date有一个iscalendar()方法,它返回一个包含日历周的元组:
>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24
datetime.date. iscalendar()是一个实例方法,返回一个元组,其中包含给定日期实例的年份、周号和星期。
在Python 3.9+中,iscalendar()返回一个包含年份、星期和星期的命名元组,这意味着您可以使用命名属性显式地访问星期:
>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar().week
24
我们也有类似的问题,于是我们想出了这个逻辑 我已经测试了1年的测试用例,并且全部通过
import datetime
def week_of_month(dt):
first_day = dt.replace(day=1)
dom = dt.day
if first_day.weekday() == 6:
adjusted_dom = dom
else:
adjusted_dom = dom + first_day.weekday()
if adjusted_dom % 7 == 0 and first_day.weekday() != 6:
value = adjusted_dom / 7.0 + 1
elif first_day.weekday() == 6 and adjusted_dom % 7 == 0 and adjusted_dom == 7:
value = 1
else:
value = int(ceil(adjusted_dom / 7.0))
return int(value)
year = 2020
month = 01
date = 01
date_value = datetime.datetime(year, month, date).date()
no = week_of_month(date_value)
我相信date. iscalendar()将是答案。本文解释了ISO 8601日历背后的数学原理。查看Python文档的datetime页面的date. iscalendar()部分。
>>> dt = datetime.date(2010, 6, 16)
>>> wk = dt.isocalendar()[1]
24
. iscalendar()返回一个三元组,包含(年,星期数,星期天数)。dt. iscalendar()[0]返回年份,dt. iscalendar()[1]返回周数,dt. iscalendar()[2]返回周数。尽可能的简单。
如果你想改变一周的第一天,你可以使用日历模块。
import calendar
import datetime
calendar.setfirstweekday(calendar.WEDNESDAY)
isodate = datetime.datetime.strptime(sweek,"%Y-%m-%d").isocalendar()
week_of_year = isodate[1]
例如,计算从周三开始的一周的冲刺数:
def calculate_sprint(sweek):
calendar.setfirstweekday(calendar.WEDNESDAY)
isodate=datetime.datetime.strptime(sweek,"%Y-%m-%d").isocalendar()
return "{year}-{month}".format(year=isodate[0], month=isodate[1])
calculate_sprint('2021-01-01')
>>>'2020-53'
对于一年中的瞬时周的整数值,尝试:
import datetime
datetime.datetime.utcnow().isocalendar()[1]
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录