Home > OS >  creating a program that takes my age or date of birth and calculate how many months days and hours l
creating a program that takes my age or date of birth and calculate how many months days and hours l

Time:10-17

I want to write a program in python that takes my age or my date of birth and tells the user how many years, months, days, and seconds he has lived so far.... I have written an algorithm but I need help with the logic can I please get some suggestions or ways to solve this program. Regards.

CodePudding user response:

You can use Python's datetime module to make an object for the current time and for the time they were born based on input, then if you take them away (just using - syntax) from each other, you get a 'timedelta' which can be used to output the months, days and hours

CodePudding user response:

You can use relativedelta from dateutil to calculate years, months etc...


import datetime
from dateutil.relativedelta import relativedelta
from datetime import date

a = '2001-04-15 12:00:00'

# converts given string to datetime object
start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
today = date.today()

diff = relativedelta(start, today)

print (diff)

output

relativedelta(years=-20, months=-6, days=-1, hours=-12)

you can get diff.years, diff.months, diff.days and diff.hours to get individual values

CodePudding user response:

I think the easiest and fastest way would be using the datetime and relativetimedelta modules. Otherwise, you'd have to do a few calculations and add extra and unnecessary lines to the code.

The datetime module produces datetime object containing all the information from a date object and a time object. You can do a lot of stuff with it, including creating a calendar.

The relativetimedelta is designed to be applied to an existing datetime and can replace specific components of that datetime, or represents an interval of time, which is what we want here, to create an interval between the date the user input and the current date.

import datetime
from datetime import date
from dateutil.relativedelta import relativedelta
    
print("Enter birthday in the following format:\nYYYY-MM-DD HH:MM:SS") #for this to work, we need to instruct the user to enter the date and time exactly as specified; otherwise, it won't work.
bday = input() #this means the user has to input the time of birth, including the seconds. 

counter = datetime.datetime.strptime(bday, '%Y-%m-%d %H:%M:%S')
todays_date = date.today()
your_bday = relativedelta(counter, todays_date)

print(your_bday)
  • Related