【问题标题】:datetime : ValueError: day is out of range for monthdatetime : ValueError: day is out of range for month
【发布时间】:2021-03-30 04:15:44
【问题描述】:

我正在编写的脚本需要两个日期并返回它们之间的持续时间,它使用 datetime 内置模块。

import datetime
print('Enter the dates [DD/MM/YYYY]!')

date1 = input('Date 1: ')
date2 = input('Date 2: ')

year1 = int(date1[6:])
month1 = int(date1[3:5])
day1 = int(date1[:2])

year2 = int(date2[6:])
month2 = int(date2[3:5])
day2 = int(date2[:2])

date1 = datetime.date(day1, month1, year1)
date2 = datetime.date(day2, month2, year2)

print(date1 - date2)

它一直在向我展示

ValueError: day is out of range for month.

【问题讨论】:

    标签: python python-3.x datetime python-datetime valueerror


    【解决方案1】:

    您以错误的顺序提供 date 构造函数的参数。 date 接受参数,yearmonthday,即:

    date1 = datetime.date(year1, month1, day1)
    date2 = datetime.date(year2, month2, day2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-03
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多