Python中如何获取明天的datetime.date类型对象且不使用timedelta
Python 无timedelta获取明日date对象方案
以下方案返回的对象为标准datetime.date类型,与datetime.date.today()返回值类型完全一致,原生支持strftime()方法,全程未使用timedelta做日期偏移计算。
实现代码
import datetime # 闰年判断工具函数 def is_leap_year(year: int) -> bool: return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def get_tomorrow_date() -> datetime.date: today = datetime.date.today() year, month, day = today.year, today.month, today.day # 各月天数配置 month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if is_leap_year(year): month_days[1] = 29 current_month_max = month_days[month - 1] # 日期进位逻辑 if day < current_month_max: return datetime.date(year, month, day + 1) else: if month == 12: return datetime.date(year + 1, 1, 1) return datetime.date(year, month + 1, 1)
使用示例
tomorrow = get_tomorrow_date() # 直接调用strftime方法 print(tomorrow.strftime("%Y年%m月%d日")) # 验证类型一致性 print(type(tomorrow) == type(datetime.date.today())) # 输出为True
内容的提问来源于stack exchange,提问作者Shelef tavor
相关产品推荐
相关产品推荐

