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}")
Related
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
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.
guys, I'm doing a problem to enter a date of birth in the format dd/mm/yyyy
The instructions to follow are
Prompt the user to enter a date of birth below.
Extract the 3 fields by slicing the string into 3 slices. To separate the day from the month, you will need to first use the find() method to find the position of the first slash. To separate the month from the year, you will need to use the rfind() method to find the position of the last slash.
I've tried to do string slices and concatenation alongside indexing, but am quite shaky on how to do it, or if I'm even doing it. Were also not allowed to use conditional statements.
birthday = input("Enter your date of birth: ",)
day = birthday.find("/")
month = birthday.find("/")
year = birthday.rfind("/")
print("Day: ",day)
print("Month: ", month)
print("Year: ", year)
The format expected is:
Enter your date of birth: 30/8/1985
Day: 30
Month: 8
Year: 1985
Using rfind() is a roundabout way to do it. It will work, but you would be better off with
day, month, year = birthday.split("/")
If your instructor insists on the find/rfind approach then you can do it this way:
day = birthday[:birthday.find("/")]
month = birthday[birthday.find("/")+1:birthday.rfind("/")]
year = birthday[birthday.rfind("/")+1:]
It might be that the intention of the exercise is to teach you about slicing strings rather than how to write readable Python.
If you have further processing of date, datetime module is useful:
from datetime import datetime
birthday = input("Enter your date of birth: ")
bday = datetime.strptime(birthday, '%d/%m/%Y')
print(f'Day: {bday.day}')
print(f'Month: {bday.month}')
print(f'Year: {bday.year}')
An important advantage is that this helps prevent user from entering wrong date, for example 32 as day or 13 as month value.
Read from docs about find and rfind. They return the lowest and the highest indexes of found occurrences. So you should do instead:
b = "30/8/1985"
first_sep, last_sep = b.find("/"), b.rfind("/")
day = b[:first_sep]
month = b[first_sep+1:last_sep]
year = b[last_sep+1:]
print("Day: ", day)
print("Month: ", month)
print("Year: ", year)
Output:
Day: 30
Month: 8
Year: 1985
birthday = input("Enter your date of birth: ",)
birthday_list = birthday.split("/")
print("Day: ",birthday_list[0])
print("Month: ", birthday_list[1])
print("Year: ", birthday_list[2])
You can use regex.
birthday = input("Enter your date of birth: ",)
match = re.search(r'\d{4}-\d{2}-\d{2}', birthday)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()
Then you can get day, month, year from that.
Please refer https://docs.python.org/3/library/datetime.html#date-objects
This works spendidly:
import datetime
birthday = input('Enter your birthday in dd/mm/yyyy format')
day, month, year = list(map(int, birthday.split("/")))
birthdate = datetime.date(year, month, day)
print(f"Birthday is on {birthdate.strftime('%d/%m/%Y')}")
I am trying to create a program in python that tells you how many days you have lived for. The code I have at the moment is:
import datetime
from datetime import timedelta
year = int(input('Enter the year'))
month = int(input('Enter the month'))
day = int(input('Enter the day'))
date1 = datetime.date(year, month, day)
now = datetime.datetime.now().date()
days = now - date1
print days
At the moment it prints the number the number of days and then 0:00:00. For example: 5914 days, 0:00:00. Does anyone know how to get rid of the 0:00:00?
days is a timedelta object, so just do print days.days
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.