Home > Net >  prgram to check number of days between starting and ending year
prgram to check number of days between starting and ending year

Time:04-24

i am trying to write a program where I need the user to input a starting year and ending year and then the program calculates the number of days between the years. I have tried to attempt this and am a little stuck. I am required to also work out if the time includes leap years aswell. if anyone is able to help me out would be appreciated.

  • The output should be as follows :

Year 1 :1980

Year 2: 2022

Number of days : 15706

import datetime
firstDate = input("Year 1?")
secondDate = input("Year 2?")
firstDateObj = datetime.datetime.strptime(firstDate, "%Y-%m-%d")
secondDateObj = datetime.datetime.strptime(secondDate, "%Y-%m-%d")
totalDays = (firstDateObj – secondDateObj).days
print(totalDays, "Day(s)")
except ValueError as e:
print(e)

thanks

CodePudding user response:

Try using the datetime.date method:

Using this method you can just take the first of January of each year:

from datetime import date
first_year = input("Year 1? ")
second_year = input("Year 2? ")
first_date = date(int(first_year), 1, 1)
second_date = date(int(second_year), 1, 1)

Subtracting these elements returns a datetime.timedelta object -

between_days = second_date - first_date
print(between_days.days)
  • Related