I am working on a small project where the code will approximately calculate what the date will be when they are one billion seconds old. I am done but I have a problem. If a user enters "5" as month or higher, then the month will exceed 12. Same for the date, it will go over 31 days if the user enters "24" or higher. How do I make it so that it will not go above "12" for months and "31" for days. Only problem is the month and the day, the year is working fine. Thanks!
When running the code, a sample you can use is, "10" as month, "24" as day and "2020" for year.
Code:
month = int(input("What Month Were You Born In: "))
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))
sum1 = day + 7
sum2 = month + 8
sum3 = year + 32
print("You will be a billion seconds old approximately around, " + str(sum1) + "/" + str(sum2) + "/" + str(sum3))
While you could do this using if statements, it's cleaner to use the datetime built-in library, which natively handles dates.
import datetime # imports it so it can be used
month = int(input("What Month Were You Born In: ")) #your code
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))
born = datetime.datetime(year, month, day)#creates a datetime object which contains a date. Time defaults to midnight.
output = born + datetime.timedelta(seconds = 1_000_000_000)#defines and applies a difference of 1 billion seconds to the date
print(output.strftime("%m/%d/%Y")) #prints month/day/year
If you do want to do it without datetime, you can use this:
month = int(input("What Month Were You Born In: "))
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))
sum1 = day + 7
sum2 = month + 8
sum3 = year + 32
if sum1 > 31: # checks if day is too high, and if it is, corrects that and addr 1 to the month to account for that.
sum1 -= 31
sum2 += 1
if sum2 > 12: #does the same thing for month
sum2 -= 12
sum3 += 1
print("You will be a billion seconds old approximately around, " + str(sum1) + "/" + str(sum2) + "/" + str(sum3))
Note that this option is less precise than the datetime option, since it doesn't take into account leapyears or various lengths of months.
You should use the datetime module to correctly handle dates which will handle issues like this.
timedelta will allow you to add, subtract etc on datetime objects.
from datetime import datetime, timedelta
month = 6
day = 24
year = 1990
born = datetime(month=month, year=year, day=day)
billion = born + timedelta(seconds=1000000000)
print(billion)
#datetime.datetime(2022, 3, 2, 1, 46, 40)
print(billion.strftime('%d/%m/%Y'))
#'02/03/2022'
Related
I have made a script to show the difference between today's date and a date you put in and ended it with the print function and an f string.
from datetime import datetime
today = datetime.today()
print("Please enter the date you want to find out how many days until below: ")
year = int(input("What year? "))
month = int(input("What month? "))
day = int(input("What day? "))
date2 = datetime(year, month, day)
difference = date2 - today
print(f"There are only {difference.days+1} days left until {date2} from {today}")
it prints the correct data however it shows the time aswell.
so it shows this as an example:
"There are only 96 days left until 2023-02-23 00:00:00 from 2022-11-19 00:14:18.003365"
how do I remove the time?
also if there are any other suggestions on improving this I'm all ears.
You could use date for this calculation.
from datetime import date
today = date.today()
print("Please enter the date you want to find out how many days until below: ")
year = int(input("What year? "))
month = int(input("What month? "))
day = int(input("What day? "))
date2 = date(year, month, day)
difference = date2 - today
print(f"There are only {difference.days+1} days left until {date2} from {today}")
I am trying to find the difference between two times and see what it is as a percentage of the year. I am subtracting a future date from today's date. For example, if the future date is two days from now, I would subtract the two dates and compute that the difference is 2. Then I would like to divide it by 365 and obtain the percentage 0.5%
So far, I managed to find the difference between two dates, however when I try to divide I just get a time as the output. Here is my code below and the outputs:
import time
import datetime
from datetime import datetime, timedelta
#Time to Expiration:
expTime = input("What is the date of expiry (yyyy-mm-dd)?: ")
expTime = datetime.strptime(expTime, "%Y-%m-%d")
today = datetime.today()
duration = expTime - today
duration_in_s = duration.total_seconds()
daysRemaining = duration.days
daysRemaining = divmod(duration_in_s, 86400)[0]
daysRemaining = (expTime - today)
#Days remaining as a percentage of the year
t = daysRemaining/365.0
print(t)
Output:
What is the date of expiry (yyyy-mm-dd)?: 2021-09-21
print(t)
6:21:03.861188
print(daysRemaining)
96 days, 14:08:29.333438
Also, if I would just like days remaining, how would I get rid of the timestamp?
Thank you!
ANSWER:
I modified my code based on the comments and answers given to:
#Time to Expiration:
expTime = input("What is the date of expiry (yyyy-mm-dd)?: ")
expTime = datetime.strptime(expTime, "%Y-%m-%d")
today = datetime.today()
daysRemaining = (expTime - today)
print("There are", daysRemaining,"days until expiration.")
#Days remaining as a percentage of the year
daysRemaining = round(((daysRemaining.total_seconds()/86400/365.24)*100),3)
print("This is", daysRemaining, "% of the year.")
this is not the best way but you can make something like this :
import datetime
today = datetime.date.today()
future = datetime.date(2021,6,20)
diff = future - today
diff = diff.days
percentage = diff/365
from datetime import datetime
x = input("first date: ")
y = input("second date: ")
a = datetime.strptime(x, "%Y/%m/%d")
b = datetime.strptime(y, "%Y/%m/%d")
result = (a-b).days
print("days: ",result)
# my first date is = 2021/2/8
# my second date is = 2021/1/24
# output = days : 15
So as you see everything is fine in this code But my teacher make a challenge for me . He said can you write a code with unusual days in months . For ex : January have 31 days but I want it to be 41 days and etc .
What should I do now ? (Please don't say : sum the output with 10 because the user inputs could be changeable and I should change all of the days in months so this will not work)
I am amatuar in coding so simple explanation would be better.
So I am looking for something like this :
# if January have 41 days instead of 31 days
# my first date is = 2021/2/8
# my second date is = 2021/1/24
# output will be = days : 15 + 10 = 25
You can make dictionary consisting of months and their custom days (For example, '1': 41 means first month consisting of 41 days). Then all you need to do is to add input date of the first month with the subtraction of total days of current month and days of input date. (Assuming first date is always greater than the second).
months = {
'1': 41,
'2': 38,
'3': 24,
...
...
'12': 45,
}
x = input("first date: ")
y = input("second date: ")
a = list(x.split('/'))
b = list(y.split('/'))
# 2021/2/8
# ['2021', '2', '8']
result = int(a[2]) + (months[b[1]] - int(b[2]))
print(result)
I think you're close the answer.
you don't want to 'sum the output with 10', but why not?
the answer to the problem is 'result + extra_days' (so sum of output + offset).
So instead of the '10' you want the offset, the offset is maxDayOfMonth +/- requestedDate
Here is a related post which gives a function to get the last day of any month:
def last_day_of_month(any_day):
# this will never fail
# get close to the end of the month for any day, and add 4 days 'over'
next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
# subtract the number of remaining 'overage' days to get last day of current month, or said programattically said, the previous day of the first of next month
return next_month - datetime.timedelta(days=next_month.day)
It always helps to find a scenario for your problem, for example:
Your teacher discoverd an alternate universe where the days in a month are variable, and he wants to use the datetime library to work. :)
I want to replicate the trick Paul Erdoes used to pull as a child:
Tell someone how many seconds he is old, based on his date of birth and the current time.
This is what the current code looks like:
# For displaying age in seconds
from datetime import datetime
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
# This is resulting in datetime.timedelta object with attr days, seconds, microseconds
#delta = datetime.now() - datetime(year, month, day)
print("You are " + str(datetime.now() - datetime(year, month, day)) + " seconds old.")
#str(delta.seconds)
Result is something around 770xx seconds, but that is incorrect, as each day is already 36000 * 24 seconds.
So how do I use the datetime library to perform what I want to do?
You can use total_seconds to calculate the difference in seconds between two dates
from datetime import datetime
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
#Calculate time in seconds between now and the day of birth
time_in_seconds = (datetime.now() - datetime(year=year, month=month, day=day)).total_seconds()
print("You are {} seconds old.".format(time_in_seconds))
The output will be
year: 1991
month: 1
day: 31
You are 892979995.504128 seconds old.
I need to write a function that that takes four arguments: day, month, and year as numbers. Weeks must be one of the following: MTWRFSU and converts this date into a human-readable string.
The output should look like:
Enter day: 28
Enter month: 9
Enter Year: 2014
Enter weekday: U
Date is: Sunday, September 28,2014.
So far my code looks like this and I am pretty stumped can anyone help an average programmer out?:
#FUNCTION THAT TAKES 4 ARGUMENTS.
day = int(input('Enter day: '))
month = int(input('Enter month: '))
year = int(input('Enter year:'))
weekday = str(input('Enter weekday: ')) #MTWRFSU
def total():
day = int(input('Enter day: '))
if day >= 32:
month = int(input('Enter month: '))
else:
print('Please enter a valid day for a month. Numbers 1 through 31.')
if month >= 12:
year = int(input('Enter Year: '))
else:
print('Please enter a valid month: ')
total()
import datetime
def total(day, month, year):
date = datetime.date(year, month, day)
return '{0:%A}, {0:%B} {0:%d}, {0:%Y}'.format(date)
day = int(raw_input("Please enter the day (1-31)"))
month = int(raw_input("Please enter the month (1-12)"))
year = int(raw_input("Please enter the year"))
print total(day, month, year)
This uses python's datetime module to handle dates. The return line uses string formatting, where {0:?} refers to the first (only) thing inside of .format() and then formats it appropriately (for month, day and year)
Also, don't use input in python 2.x (if this is python 3.x then go ahead)
You might notice that I only use 3 inputs - that's because datetime can figure out the day of the week without being told. This can be trivially changed to ask for that as well, however.