python,如何检查日期是否在下周

2024-06-28 14:50:17 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我试图检查一个日期,例如2021-07-08,是在下一周,还是在下一周之后,或者两者都不在

#I can call the start and end dates of the current week

start = tday - timedelta(days=tday.weekday())
end = start + timedelta(days=6)
print("Today: " + str(tday))
print("Start: " + str(start))
print("End: " + str(end))

# and I can get the current week number. 

curr_week = datetime.date.today().strftime("%V")
print(curr_week)

有没有比在curr_week+1中获取日期列表,然后检查该列表中是否有日期更好的方法? 非常感谢


Tags: andthe列表currentcalldaysstartcan
3条回答

[参见阿尔弗雷德的答案]

您可以直接从每个日期的IsoCalendarDate表示中获取整数形式的周数

from datetime import datetime
date_format = '%Y-%m-%d'
t_now = datetime.strptime('2021-08-11', date_format)
target_date = datetime.strptime('2021-08-18', date_format)

您可以在datetime中强制转换要签入的日期,然后比较周数

# date you want to check
date = datetime.datetime.strptime("2021-07-08","%Y-%m-%d")

# current date
tday = datetime.date.today()

# compare the weeks
print(date.strftime("%V"))
print(tday.strftime("%V"))

27
32

一般答复

最好坚持使用datetime和timedelta,因为这可以处理所有的边缘情况,如年份变化、有53周的年份等

因此,找出下周的数字,并将你想要检查的周数与之进行比较

import datetime

# Date to check in date format:
check_date = datetime.datetime.strptime("2021-09-08", "%Y-%d-%m").date()

# Current week number:
curr_week = datetime.date.today().strftime("%V")
# number of next week
next_week = (datetime.date.today()+datetime.timedelta(weeks=1)).strftime("%V")
# number of the week after that
week_after_next_week = (datetime.date.today()+datetime.timedelta(weeks=2)).strftime("%V")


# Compare week numbers of next weeks to the week number of the date to check:
if next_week == check_date.strftime("%V"):
    # Date is within next week, put code here
    pass
elif week_after_next_week == check_date.strftime("%V"):
    # Date is the week after next week, put code here
    pass

旧答案

这会把年份的变化搞得一团糟,而模运算并不能解决这个问题,因为有53周的年份

您可以通过将周数转换为整数来比较周数。您不需要创建下周内所有日期的列表

import datetime

# Date to check in date format:
check_date = datetime.datetime.strptime("2021-07-08", "%Y-%d-%m").date()

# Current week number, make it modulo so that the last week is week 0:
curr_week = int(datetime.date.today().strftime("%V"))

# Compare week numbers:
if curr_week == (int(check_date.strftime("%V"))-1):
    # Date is within next week, put code here
    pass
elif curr_week == (int(check_date.strftime("%V"))-2):
    # Date is the week after next week, put code here
    pass

相关问题 更多 >