简体   繁体   中英

datetime : ValueError: day is out of range for month

The script I'm writing takes two dates and gives back the duration between them, it uses the datetime built-in module.

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)

It keeps showing me

ValueError: day is out of range for month.

You're providing the date constructor's arguments in the wrong order. date takes the arguments, year , month , day , ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM