AstroBoy91
AstroBoy91

Reputation: 5

Birthdate + Number of days = date

I'm having a hard time writing a python program that takes the inputs of a date of birth (mm-dd-yyyy) and a number of days (ex: 5000) and printing out the date the person with the date of birth will reach that number of days. For example, if I enter "05-12-1960" and "30000", I should get 07-01-2042. So far, I have been able to get the input functions for date of birth and the number of days:

birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
    days = input("Enter a number of days: ")

I'm recently new to python, so I'm still trying to learn other functions such as str, input, int, etc. Do I start with a counter or if/else statements? I appreciate any feedback.

Upvotes: 0

Views: 983

Answers (4)

Tyler V
Tyler V

Reputation: 10910

You can use the datetime module to convert a date string into a date object, then use timedelta to increment it by some number of days.

Error handling is important here too. If you are doing these operations with user input strings, adding some validation that the user actually entered a valid date and integer is important too or the program will crash if they enter an invalid entry.

Here is an example:

import datetime

def get_birthday():
    """Get the birthday, catch if it is not a valid date and ask again"""
    while True:
        birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
        try:
            return datetime.datetime.strptime(birthdate, "%m-%d-%Y")
        except ValueError:
            print(f"'{birthdate}' is not a valid date, try again")

def get_num_days():
    """Get the number of days, catch if it is not a valid integer and ask again"""
    while True:
        days = input("Enter a number of days: ")
        try:
            return int(days)
        except ValueError:
            print(f"'{days}' is not an integer, try again")
                
date = get_birthday()
num_days = get_num_days()

date += datetime.timedelta(days = num_days)
new_date_str = date.strftime("%m-%d-%Y")
print(f"The new date is {new_date_str}")

Upvotes: 1

Dima Chubarov
Dima Chubarov

Reputation: 17159

In Python you should start learning the modules available in the Python Standard Library. For your task you may use the datetime module.

from datetime import datetime, timedelta

# Your input functions
birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
days = input("Enter a number of days: ")

# Using the calendar functions from datetime module
dateformat = '%m-%d-%Y'
# redefining a name is usually not a good practice
birthdate = datetime.strptime(birthdate, dateformat) 
newdate = birthdate + timedelta(days = int(days))
print(newdate.strftime(dateformat))

Upvotes: 0

Venfah Nazir
Venfah Nazir

Reputation: 330

[root@cscale-82-69 python]# cat dateime.py 
from datetime import datetime
from datetime import timedelta
  
startdate = datetime.strptime("2022-5-1", "%Y-%m-%d")
print(startdate)
finaldate = startdate + timedelta(days=5000)
print(finaldate)

Sample output

[root@cscale-82-69 python]# python dateime.py
2022-05-01 00:00:00
2036-01-08 00:00:00
[root@cscale-82-69 python]# 

Upvotes: 0

Eric Jin
Eric Jin

Reputation: 3924

You can use datetime to parse the datetimes.

import datetime

birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
days = input("Enter a number of days: ")

birthdate = ''.join([birthdate[i] for i in (6, 7, 8, 9, 2, 0, 1, 2, 3, 4)])  # reorder the string to convert `mm-dd-yyyy` to `yyyy-mm-dd`
birthtime = datetime.datetime.fromisoformat(birthdate).timestamp()  # get timestamp in seconds
time_after = birthtime + int(days)*86400
new = datetime.datetime.fromtimestamp(time_after)

# do things
print(f'It will be {new.year}, month {new.month} day {new.day}')

Output:

Enter your date of birth (mm-dd-yyyy): 01-01-2022
Enter a number of days: 14
It will be 2022, month 1 day 15

Upvotes: 0

Related Questions