Python判断yyyy-mm-dd格式日期所属时间阶段的问题排查
问题原因与解决方案
问题根源
你的代码里,datetime.strptime(date_string, '%Y-%m-%d')解析出的this_date是目标日期当天00:00:00的datetime对象,而datetime.today()返回的是当前精确到秒的实时时间(比如测试时的15:40:30)。哪怕是同一天,00:00的时间也必然小于当前实时时间,所以当天日期会被误判为过去。
修正方案
有两种简单的修复方式,核心都是让两边的比较维度一致:
方法一:仅比较日期对象(推荐)
把datetime对象转换为date对象,只保留年、月、日信息进行比较:
from datetime import datetime def check_date(date_string): this_date = datetime.strptime(date_string, '%Y-%m-%d').date() now = datetime.today().date() if this_date < now: print("the date is in the past") elif this_date > now: print("the day is in the future") else: print("the day is today")
方法二:统一时间到当天零点
将当前时间截断到当天00:00:00,再和解析出的datetime对象比较:
from datetime import datetime def check_date(date_string): this_date = datetime.strptime(date_string, '%Y-%m-%d') # 把当前时间的时分秒微秒都置为0 now = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) if this_date < now: print("the date is in the past") elif this_date > now: print("the day is in the future") else: print("the day is today")
测试修正后的代码,调用check_date('2022-09-22')就会正确输出"the day is today"。
内容的提问来源于stack exchange,提问作者user19245296
相关产品推荐
相关产品推荐

