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

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")

Related

Credit system for Pension calculator (Python3)

A Pension in simplest terms is an amount of money paid to an employee agreed upon from an employer based on how long they worked.
The code I have below is the code based off input data (Year Start Employment, Month Start, day Start) the same goes for the date the year ended.
Then I have a loop that goes through every single year and counts the amount of days you worked for that year between both dates.
Let us say for this EXAMPLE:
-The Date Started: January 2, 2020
-The Date Ended: June 23,2023
from datetime import timedelta, date
#For the Input Information
#Beginning Dates
print("===============================START WORK DATE INFO======================================\n")
YearStartEMP = int(input("Please Enter The Year Employment Started:"))
MonthStartEMP = int(input("Please Enter The Month Employment Started:"))
StartDayEmp = int(input("Please Enter The Day # Employment Started:"))
#End of Work dates
print("===============================END WORK DATE INFO======================================\n")
YearEndEMP = int(input("Please Enter The Year Employment Ended:"))
MonthEndEMP = int(input("Please Enter The Month Employment Ended:"))
EndDayEmp = int(input("Please Enter The Day# Employment Ended:"))
print("===============================DAYS PER YEAR WORKED=======================================\n")
#dates entered
StartWork = date(YearStartEMP, MonthStartEMP, StartDayEmp)
EndWork = date(YearEndEMP, MonthEndEMP, EndDayEmp) + timedelta(days=1)
#While loop to look through each year and count the days per year for each year betwwen dates
while StartWork < EndWork:
next_year = StartWork.replace(year=StartWork.year + 1, month=1, day=1)
if next_year < EndWork:
diff = next_year - StartWork
else:
diff = EndWork - StartWork
print(f'{StartWork.year}: {diff.days} days')
StartWork = next_year
This is what the Output would look like off the information I have given.
===============================START WORK DATE INFO=======================================
Please Enter The Year Employment Started:2020
Please Enter The Month Employment Started:1
Please Enter The Day # Employment Started:2
===============================END WORK DATE INFO=========================================
Please Enter The Year Employment Ended:2023
Please Enter The Month Employment Ended:6
Please Enter The Day# Employment Ended:23
===============================DAYS PER YEAR WORKED=======================================
2020: 365 days
2021: 365 days
2022: 365 days
2023: 174 days
The question I have is what code or function should I use for the part of code under "===DAYS PER YEAR WORKED===" to make the output look like this. what kind of if statements or functions should I use ASSUMING that a retiree only needs 180 days to get the credit for the year. It should look something like this.
2020: 365 days, 1 credit
2021: 365 days, 1 Credit
2022: 365 days, 1 Credit
2023: 174 days, 0 Credit
or something like this:
2020: 365 days
2021: 365 days
2022: 365 days
2023: 174 days
2020: 1 credit
2021: 1 Credit
2022: 1 Credit
2023: 0 Credit
I've tried doing this but it resulted in an error:
if DateBracket >= 180:
Credit = 1
print("1 credit")
elif DateBracket < 180:
Credit = 0
print("0 credit")
Here's your working code. I added some comments to explain the changes I made:
from datetime import timedelta, date
# For the Input Information
# Beginning Dates
print("===============================START WORK DATE INFO======================================\n")
# Added the `.strip()` method to remove whitespaces from the input
YearStartEMP = int(input("Please Enter The Year Employment Started: ").strip())
MonthStartEMP = int(input("Please Enter The Month Employment Started: ").strip())
StartDayEmp = int(input("Please Enter The Day # Employment Started: ").strip())
# End of Work dates
print("===============================END WORK DATE INFO======================================\n")
YearEndEMP = int(input("Please Enter The Year Employment Ended: ").strip())
MonthEndEMP = int(input("Please Enter The Month Employment Ended: ").strip())
EndDayEmp = int(input("Please Enter The Day # Employment Ended: ").strip())
print("===============================DAYS PER YEAR WORKED=======================================\n")
# Dates entered
StartWork = date(YearStartEMP, MonthStartEMP, StartDayEmp)
EndWork = date(YearEndEMP, MonthEndEMP, EndDayEmp) + timedelta(days=1)
# Also keep track of the total number of credits for simplicity
total_credits = 0
# While loop to look through each year and count the days per year for each year betwwen dates
while StartWork < EndWork:
next_year = StartWork.replace(year=StartWork.year + 1, month=1, day=1)
if next_year < EndWork:
# We only need the number of days worked in this year, not the whole timedelta
days_per_year = (next_year - StartWork).days
else:
days_per_year = (EndWork - StartWork).days
# Set `credits` to 1 if the employee worked at least 180 days in the year
# Else, set `credits` to 0
credits = 1 if days_per_year >= 180 else 0
# The code above is equivalent to the following, but it's cleaner
"""
if days_per_year >= 180:
credits = 1
else:
credits = 0
"""
# Also print the credits for the year
print(f'{StartWork.year}: {days_per_year} days, {credits} credit(s)')
StartWork = next_year
# Update the total number of credits
total_credits += credits
print(f'Total credits: {total_credits}')
And here's the sample output:
===============================START WORK DATE INFO======================================
Please Enter The Year Employment Started: 2020
Please Enter The Month Employment Started: 1
Please Enter The Day # Employment Started: 2
===============================END WORK DATE INFO======================================
Please Enter The Year Employment Ended: 2023
Please Enter The Month Employment Ended: 6
Please Enter The Day # Employment Ended: 23
===============================DAYS PER YEAR WORKED=======================================
2020: 365 days, 1 credit(s)
2021: 365 days, 1 credit(s)
2022: 365 days, 1 credit(s)
2023: 174 days, 0 credit(s)
Total credits: 3

Check if date is between two dates without year included

I have a datetime date in the format yyyy-mm-dd and I want to check if the date entered falls between for example May 15th and May 25th without including any year value.
tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))
import datetime
tripDate = datetime.datetime.strptime(tripDate_str, "%Y-%m-%d")
Well I guess the simplest approach is to use the month and day date class attributes
import datetime
tripDate = datetime.datetime.strptime('2022-05-15', "%Y-%m-%d")
start = datetime.datetime.strptime('2022-05-10', "%Y-%m-%d")
end = datetime.datetime.strptime('2022-05-20', "%Y-%m-%d")
if tripDate.month >= start.month and tripDate.month <= end.month and tripDate.day >= start.day and tripDate.day <= end.day:
print('Date in range')
else:
print('Date not in range')
There are many options to get the day of the year from a date. Use a search engine with keywords python day of year to find out which or just look here at stackoverflow ("Convert Year/Month/Day to Day of Year in Python"). The code below is using for this purpose dateObject.timetuple().tm_yday:
tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))
# tripDate_str = "2022-05-18"
## Finding day of year
from datetime import date
tripDate = date(*map(int, tripDate_str.split('-')))
tripDate_dayOfYear = tripDate.timetuple().tm_yday
print("Day of year: ", tripDate_dayOfYear, type(tripDate_dayOfYear))
dateRangeBeg_dayOfYear = date(tripDate.year, 5, 15).timetuple().tm_yday
dateRangeEnd_dayOfYear = date(tripDate.year, 5, 25).timetuple().tm_yday
if dateRangeBeg_dayOfYear <= tripDate_dayOfYear <= dateRangeEnd_dayOfYear:
print("tripDate falls into range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)
else:
print("tripDate is outside range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)
To avoid a problem with leap years tripDate.year is used in setting the values of dateRangeBeg_dayOfYear and dateRangeEnd_dayOfYear.

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.

Why is my program outputting the wrong number of days?

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.

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.

Categories