I am trying to find out when someone will turn 1 billion seconds old. the user inputs when they were born. These values are then converted to seconds and then I add 1 billion seconds and convert back into a date. However, when I enter certain dates, python seems to mess up. Such an example is 1993/11/05 00:00:00 where python says the user will turn in the 0th month.
Note I cant use if/else or datetime.
Heres my code:
YEARSEC=(12*30*24*3600)
MONTHSEC=(3600*24*30)
DAYSEC=(24*3600)
HOURSEC=3600
MINUTESEC=60
year=int(input("Please enter the year in which you were born: "))
month=int(input("Please enter the month you were born: "))
day=int(input("Please enter the day you were born: "))
hour=int(input("Please enter the hour you were born: "))
minute=int(input("Please enter the minute you were born: "))
second=int(input("Please enter the second you were born: "))
year_calc=(year*YEARSEC)
month_calc=(month*MONTHSEC)
day_calc=(day*DAYSEC)
hour_calc=(hour*HOURSEC)
minute_calc=(minute*MINUTESEC)
s=(1000000000+year_calc+month_calc+day_calc+hour_calc+minute_calc+second)
year_num=int((s/YEARSEC))
s=(s-(year_num*YEARSEC))
month_num=int((s/MONTHSEC))
s=(s-(month_num*MONTHSEC))
day_num=int((s/DAYSEC))
s=(s-(DAYSEC*day_num))
hour_num=int((s/HOURSEC))
s=(s-(HOURSEC*hour_num))
minute_num=int((s/MINUTESEC))
s=(s-(MINUTESEC*minute_num))
print("You will turn 1 000 000 000 seconds old on: %04d/%02d/%02d %02d:%02d:%02d" %(year_num,month_num,day_num,hour_num,minute_num,s))
Though I have not test it all, I think you can not get Dec and day 30.
You should plus 1 to day_num and month_num cause month and day start from 1 not 0.
print("You will turn 1 000 000 000 seconds old on: %04d/%02d/%02d %02d:%02d:%02d" %(year_num,month_num+1,day_num+1,hour_num,minute_num,s))
Time calculations are tricky. Months don't all have 30 days, for example. Hours, minutes, and seconds are numbered starting from 0, but days and months are numbered starting from 1, creating off-by-one bugs in your calculations (hint, ask for month, then subtract one, do all the calculations, then add one when displaying it again). You aren't accounting for leap years either.
Best to use built-in tools, if only to check your eventual homework answer, although it looks like the teacher said to assume 30-day months ;^)
>>> import datetime
>>> birthday = datetime.datetime(1993,11,05,0,0,0)
>>> billion = birthday + datetime.timedelta(seconds=1000000000)
>>> billion.ctime()
'Mon Jul 14 01:46:40 2025'
Related
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")
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.
1. The days enterred should be after 15/10/1582
2. Should consider the leapyears.
3. Even when "ctrl + c" or alphabets are enterred, the source code should go on (Use try...except)
3. Repeat until 0 is enterred in 'year'.
THis is what I tried.....
while True:
year = int(input("Year: "))
if year == 0
break
month = int(input("Month: ")
day = int(input("Days: "))
I completely can't think of how to solve this, so I'd like to get some hints how I should deal with this problem!
Year: 2019 Month: 0 Day: 12 There is only January ~ December
Year: 2019 Month: 1 Day: 0 Day should be at least 1
Year: 2019 Month: 1 Day: 32 January is upto 31
Year: 2020 Month: 2 Day: 30 2020 is a leapyear, but Feburary is upto
29
Year: 2019 Month: 2 Day: 29 2019 is not a leapyear, so Feburary is
upto 28
Year: 1582 Month:1 Day:1 1/1/1582 is before when Gregorian calender
started
Year: 2019 Month: 1 Day:8 OK
Year: 0
Well, the first thing to do, obviously, is to check whether your user inputs are proper numerics. As mentionned in the instructions, this can be done using exception handling (try/except blocks). Exception handling is documented so first check the doc and use the interactive shell to test out things until you get how ot works... Just a couple hints here: only catch the exact exceptions you expect at a given point, and have the less possible code in the try block so you're sure you only catch the exceptions raised by this exact piece of code.
(NB : Note that this can ALSO be done without exception handling by testing the content of the strings returned by input() _before_ passing them to int(), but you're obviously expected to use exception handling here, cf the "Use try/except" mention.)
The second thing is to validate that the individual values entered for day, month and year are in the expected range; ie there are only 12 month, so for this variable, any value lower than 1 (january) or higher than 12 (december) is invalid.
Note that since the number of days in a month changes from month to month and, for february, can change from year to year, you can only validate days once you know the month and the year.
I suggest you first make the "day" validation work without taking care of leap years, and only then take care of the leap year special case. As often, a good data structure is key to simple effective code, so read about the standard basic Python data types (lists, dicts, tuples etc) and think about which of those types you could use to map a month number to how many days it has (for a non leap year, that is).
There are quite a few other things to care of, but first manage to get those first two points working and the rest should not be too difficult.
I am trying to identify the month number from a given week and year number (both are user inputs). The script needs to be written in python.
eg - 1) Yr 2017, Wk 12 results in Month# 3
2) Yr 2017, Wk 32 results in Month#8 and so on
I am a newbie and searched for all date time examples, still no clue. Any ideas? Would really appreciate the help.
Thanks in advance!
As we know the numbers of days in each month of a given year, and the number of days that span w weeks (w*7) it is sufficient to sum the days of each month until the result is greater than w*7, counting the number of months used in the sum. If we used say n months, the number you want is n
We can know if the year is a leap year as the following demonstrates.
import calendar
print calendar.isleap(2017)
I'm trying to program a salary calculator that tells you what your salary is during sick leave. In Costa Rica, where I live, salaries are paid bi-monthly (the 15th and 30th of each month), and each sick day you get paid 80% of your salary. So, the program asks you what your monthly salary is and then asks you what was the start date and finish date of your sick leave. Finally, it's meant to print out what you got paid each payday between your sick leave. This is what I have so far:
import datetime
salario = float(input("What is your monthly salary? "))
fecha1 = datetime.strptime(input('Start date of sick leave m/d/y: '), '%m/%d/%Y')
fecha2 = datetime.strptime(input('End date of sick leave m/d/y: '), '%m/%d/%Y')
diasinc = ((fecha2 - fecha1).days)
print ("Number of days in sick leave: ")
print (diasinc)
def daterange(fecha1, fecha2):
for n in range(int ((fecha2 - fecha1).days)):
yield fecha1 + timedelta(n)
for single_date in daterange(fecha1, fecha2):
print (single_date.strftime("%Y-%m-%d")) #This prints out each individual day between those dates.
I know for the salary I just multiply it by .8 to get 80% but how do I get the program to print it out for each pay day?
Thank you in advance.
Here's an old answer to a similar question from about eight years ago: python count days ignoring weekends ...
... read up on the Python: datetime module and adjust Dave Webb's generator expression to count each time the date is on the 15th or the 30th. Here's another example for counting the number of occurrences of Friday on the 13th of any month.
There are fancier ways to shortcut this calculation using modulo arithmetic. But they won't matter unless you're processing millions of these at a time on lower powered hardware and for date ranges spanning months at a time. There may even be a module somewhere that does this sort of thing, more efficiently, for you. But it might be hard for you to validate (test for correctness) as well as being hard to find.
Note that one approach which might be better in the long run would be to use Python: SQLite3 which should be included with the standard libraries of your Python distribution. Use that to generate a reference table of all dates over a broad range (from the founding of your organization until a century from now). You can add a column to that table to note all paydays and use SQL to query that table and select the dates WHERE payday==True AND date BETWEEN .... etc.
There's an example of how to SQLite: Get all dates between dates.
That approach invests some minor coding effort and some storage space into a reference table which can be used efficiently for the foreseeable future.