from datetime import datetime
# v1.0
def week_num(start_time, end_time):
week_start = datetime.strptime(start_time, '%Y-%m-%d')
week_end = datetime.strptime(end_time, '%Y-%m-%d')
# 方法1:
return week_end.isocalendar()[1] - week_start.isocalendar()[1]
# 方法2:
return int(datetime.strftime(week_end, "%W")) - int(datetime.strftime(week_start, "%W"))
print(week_num("2020-05-31", "2020-06-03"))
# 上述方法如果两个时间段超出一年, 计算结果会出现错误, v.2.0对此作出优化
# v2.0
def week_num(start_time, end_time):
week_start = datetime.strptime(start_time, '%Y-%m-%d')
week_end = datetime.strptime(end_time, '%Y-%m-%d')
# 方法1:
# year_week_num = 53 # print(datetime(2020, 12, 31).isocalendar())
# week_start_year, week_start_num, _ = week_start.isocalendar() # (年份, 年份中的第几个星期, 星期几)
# week_end_year, week_end_num, _ = week_end.isocalendar() # 53-->52
# # 方法2:
year_week_num = 52 # print(datetime.strftime(datetime(2020, 12, 31), "%W"))
week_end_year = week_end.year
week_start_year = week_start.year
week_end_num = int(datetime.strftime(week_end, "%W"))
week_start_num = int(datetime.strftime(week_start, "%W"))
return (week_end_year - week_start_year) * year_week_num + week_end_num - week_start_num
print(week_num("2021-01-01", "2021-11-24")) # 有兴趣的可以看一下方法1和方法2中 week_start_year, week_start_num 的值是不同的
"""
至于
rrule(rrule.WEEKLY, dtstart=date1, until=date2).count()
他的原理是以七天为一个时间点,然后与start和end相比较,
结果插入到列表中, 最后count列表,
这个方法有一点不好就是会把同一周的两天,计算为相差1周
例如:
import datetime as dt
from dateutil import rrule
def week_nums(d1, d2):
date1 = dt.datetime.strptime(d1, "%Y-%m-%d")
date2 = dt.datetime.strptime(d2, "%Y-%m-%d")
Weeks = rrule.rrule(rrule.WEEKLY, dtstart=date1, until=date2).count()
print(Weeks)
week_nums("2020-05-03", "2020-05-04")
""""
具体需要需要采用哪种方法,看具体的需求来定
Python : 计算两个时间点相隔几周
最新推荐文章于 2024-07-18 06:37:08 发布