-1

I am making a program where I input start date to dataStart(example 21.10.2000) and then input int days dateEnd and I convert it to another date (example 3000 = 0008-02-20)... Now I need to count these dates together, but I didn't managed myself how to do that. Here is my code.

from datetime import date 

start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))  

dataStart=start.split(".") 

days=int(dataStart[0])
months=int(dataStart[1])
years=int(dataStart[2])  

endYears=0
endMonths=0
endDays=0

dateStart = date(years, months, days)

while end>=365:
    end-=365
    endYears+=1
else:
    while end>=30:
        end-=30
        endMonths+=1
    else:
        while end>=1:
            end-=1
            endDays+=1
dateEnd = date(endYears, endMonths, endDays)
  • 1
    I'm not sure what "Now I need to count these dates together" means. Please give an example of input and what output you would expect (and why). – glibdud Sep 22 '17 at 16:49
  • Inputs are 2 dates, for example input 1 is 12.6.1997, and input two (already converted from to days to another date) is 2.3.0002.... And I want output to be 14.9.1999 @glibdud – Matej Pakán Sep 22 '17 at 16:53
  • You're immediately passing your second input to `int()`, so if you try to enter `"2.3.0002"`, you'll get a `ValueError`. – glibdud Sep 22 '17 at 16:56

3 Answers3

2

For adding days into date, you need to user datetime.timedelta

start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))  

date = datetime.strptime(start, "%d.%m.%Y")
modified_date = date + timedelta(days=end)
print(datetime.strftime(modified_date, "%d.%m.%Y"))
Dharmesh Fumakiya
  • 2,276
  • 2
  • 11
  • 17
1

You may use datetime.timedelta to add certain units of time to your datetime object.

See the answers here for code snippets: Adding 5 days to a date in Python

Alternatively, you may wish to use the third-party dateutil library if you need support for time additions in units larger than weeks. For example:

>>> from datetime import datetime
>>> from dateutil import relativedelta
>>> one_month_later = datetime(2017, 5, 1) + relativedelta.relativedelta(months=1)
>>> one_month_later
>>> datetime.datetime(2017, 6, 1, 0, 0)
Mario
  • 59
  • 6
0

It will be easier to convert to datetime using datetime.datetime.strptime and for the part about adding days just use datetime.timedelta.

Below is a small snippet on how to use it:

import datetime
start = "21.10.2000"
end = 8
dateStart = datetime.datetime.strptime(start, "%d.%m.%Y")
dateEnd = dateStart + datetime.timedelta(days=end)
dateEnd.date()  # to get the date format of the endDate

If you have any doubts please look at the documentation python3/python2.

Bernardo Duarte
  • 4,074
  • 4
  • 19
  • 34