Why is my program outputting the wrong number of days? - python

So I am writing a program to work out the number of days you have been alive after imputting your birthday. There is a problem as i am getting the wrong number of days but can figure out why. i inputted my birthday as 04/04/19 and i got 730625 days which is clearly wrong.
import datetime #imports module
year = int(input("What year were you born in"))
month = int(input("What month where you born in (number)"))
date = int(input("What date is your birthday? "))
birthdate = datetime.date(date, month, year) #converts to dd/mm/yy
today = datetime.date.today() #todays date
daysAlive = (today - birthdate).days #calculates how many days since birth
print("You have been alive for {} days.".format(daysAlive)) #outputs result

I initially got the same error as you but then I checked my code and managed to fix my mistake.
So your DOB is 04/04/19, when you input that into datetime.date() and it looks at the value for year which is 19, it will treat that as 0019. As in 19 AD, not 2019. You should make sure that you input the full year.
Also like SimonN said, the parameters for datetime.date() are year, month, day, not the other way around.

You have the parameters the wrong way round in datetime.date they should be (year,month,day)

datetime takes arguments as (year, month, date). Note that you cannot enter year like 09 for 2009. Datetime will count it as 0009-MM-DD. You have to enter complete year in the input as 2009
...
birthdate = datetime.date(year, month, date)
...
So, with your input, the output for me is (It may differ with your timezone):
You have been alive for 170 days.

class datetime.date(year, month, day)
should be in the format yy/mm/dd.
Try this code for Python 3.6 or higher,
because of f-stings:
import datetime
year = int(input("What year were you born in: "))
month = int(input("What month were you born in (number): "))
day = int(input("What day were you born in: "))
birth_date = datetime.date(year, month, day) # converts to yy/mm/dd
today = datetime.date.today() # todays date
days_alive = (today - birth_date).days # calculates how many days since birth
print(f"You are {days_alive} days old.") # outputs result
Check the answer using other sources.

Related

python - how to count down days until Birthday (between two dates) [duplicate]

This question already has answers here:
How to convert datetime to integer in python
(7 answers)
Closed 1 year ago.
The task I was given is to create a program that will check if the current date is your birthday. If it is, print "Happy Birthday!". If not then output how many days left till your birthday.
I have been struggling with this task, I think I have got it working, but how do I remove the comma "," and the time "0:00:00" output from the result?
I only want it to display the number of days and the word days.
INPUT:
1989
6
21
DESIRED OUTPUT (at time/date of asking question!):
349 days
NOT: 349 days, 0:00:00
Hope that is clear and thanks in advance!
--
So far I have:
import datetime
today = datetime.date.today()
user_birth_year = int(input("Enter year of birth i.e. 1989: "))
user_birth_month = int(input("Enter month of birth i.e. for June enter 6: "))
user_birth_day = int(input("Enter day of birth i.e. for 21st enter 21: "))
my_birthday = datetime.date(today.year, user_birth_month, user_birth_day)
if my_birthday == today:
print("Happy Birthday!")
else:
if my_birthday < today:
my_birthday = my_birthday.replace(year=today.year + 1)
days_until_birthday = my_birthday - today
print(days_until_birthday)
else:
days_until_birthday = my_birthday - today
print(days_until_birthday)
This is included in any tutorial on datetime. If you want only the days, then access the days attribute.
else:
days_until_birthday = my_birthday - today
print(days_until_birthday.days, "days")

Take a date from input and see how many days that it is from today

I'm trying to make a program that takes a date inputted by the user in 'yyyy mm dd' format and see how many days that input is from today. I have no idea how to do this but if u can help that would be great.
input("This is a function to find the difference between today and a date
you enter. Enter the date in this format: 'yyyy mm dd' ")
This should work
import datetime
today = datetime.date.today()
year = int(input('Enter a year')) #input the needed year
month = int(input('Enter a month')) #input the needed month
day = int(input('Enter a day')) #input the needed day
neededdate = datetime.date(year, month, day)
days_remaining = neededdate - today
print(days_remaining.days)
I edited to input date, month and year.

Convert int to date

I'm trying to convert yyyy/mm/dd to dd/mm/yyyy, from integer inputs.
When i've changed the pattern inside the parethesis from datetime.date(year, month, day), to datetime.date(day, month, year), it returns an Value error.
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(day, month, year)
return exp_date
ValueError: day is out of range for month
From the documentation:
class datetime.date(year, month, day)
This means you need to put the arguments in the right position, doesn't matter how you want to print it later.
This should work:
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(year, month, day)
return exp_date
Now let's print it formatted in dd/mm/yyyy:
d = acc_expiration()
f = d.strftime('%d/%m/%Y')
print(f) # prints it formatted dd/mm/yyyy
Your value error is because you are giving a year integer (integer bigger than 31) to the day argument, and for the year you are giving the day integer.
You are confusing the object from its presentation.
Look at the Python docs for Datetime (here)
The correct sequence for datetime.date is class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
Once you have a datetime object, you can format the output of it in a variety of ways to suit your needs.
Does that help?

I need To find how to subtract the current date by another date

So I am trying to make a script to tell you how long you have been alive. It al went good but I can’t find out how to subtract a birthday from the current date as shown in the total variable.
import time
## dd/mm/yyyy format
times=(time.strftime("%d/%m/%Y"))
day=(time.strftime("%d"))
month=(time.strftime("%m"))
year=(time.strftime("%Y"))
##questions
born_y=input('what year were you born')
born_m=input('what month')
born_d=input('what day')
##convert to decimal
current_time=int(year+'.'+month+'.'+day)
current_age=int(born_y+'.'+born_m+'.'+born_d)
##find age
total=current_time-current_age
print(total)
Try using datetime instead of time like this:
import datetime
year = input("What year were you born: ")
month = input("What month were you born: ")
day = input("What day were you born on: ")
born = datetime.datetime(int(year), int(month), int(day))
age = datetime.datetime.now() - born
print(age.days)
>>> 7549
You can then split thetimedelta object age up how you want, or just get the days from age.days.
Be aware that this won't work if the user inputs anything other than integers.

How can I subtract two dates in Python?

So basically what I want to do is to subtract the date of birth from todays date in order to get a persons age, I've successfully done this, but I can only get it to show the persons age in days.
dateofbirth = 19981128
dateofbirth = list(str(dateofbirth))
now = datetime.date.today()
yr = dateofbirth[:4]
yr = ''.join(map(str, yr))
month = dateofbirth[4:6]
month = ''.join(map(str, month))
day = dateofbirth[6:8]
day = ''.join(map(str, day))
birth = datetime.date(int(yr), int(month), int(day))
age = now - birth
print(age)
In this case, age comes out as days, is there any way to get it as xx years xx months and xx days?
You can use strptime:
>>> import datetime
>>> datetime.datetime.strptime('19981128', '%Y%m%d')
datetime.datetime(1998, 11, 28, 0, 0)
>>> datetime.datetime.now() - datetime.datetime.strptime('19981128', '%Y%m%d')
datetime.timedelta(5823, 81486, 986088)
>>> print (datetime.datetime.now() - datetime.datetime.strptime('19981128', '%Y%m%d'))
5823 days, 22:38:18.039365
The result of subtracting two dates in Python is a timedelta object, which just represents a duration. It doesn't "remember" when it starts, and so it can't tell you how many months have elapsed.
Consider that the period from 1st January to 1st March is "two months", and the period from 1st March to 28th April is "1 month and 28 days", but in a non-leap year they're both the same duration, 59 days. Actually, daylight savings, but let's not make this any more complicated than it needs to be to make the point ;-)
There may be a third-party library that helps you, but as far as standard Python libraries are concerned, AFAIK you'll have to roll your sleeves up and do it yourself by finding the differences of the day/month/year components of the two dates in turn. Of course, the month and day differences might be negative numbers so you'll have to deal with those cases. Recall how you were taught to do subtraction in school, and be very careful when carrying numbers from the month column to the days column, to use the correct number of days for the relevant month.

Categories