Displaying age in seconds using Python3 - python

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.

Related

date countdown not working as intended. time keeps printing

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

How to divide the difference in two times in python to find the difference as a percentage of the year?

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

How to make months not exceed 12

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'

User input of standard time converted into Julian Time

I'm stuck on how to get a users input of year, month, day and hour converted into Julian time.
This works if I code in the time like this:
from __future__ import print_function, division
from PyAstronomy import pyasl
import datetime
# Convert calendar date to JD
dt = datetime.datetime(2017, 5, 23, 10)
print("Input date: ", dt)
print("Corresponding Julian date: ", pyasl.jdcnv(dt))
print("Corresponding reduced Julian date: ", pyasl.juldate(dt))
print()
but when I try a users input like this
from __future__ import print_function, division
from PyAstronomy import pyasl
import datetime
# Convert calendar date to JD
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
hour = int(input('Enter hour'))
dt = datetime.date(year, month, day, hour)
print("Input date: ", dt)
print("Corresponding Julian date: ", pyasl.jdcnv(dt))
print("Corresponding reduced Julian date: ", pyasl.juldate(dt))
print()
I get the error
TypeError Traceback (most recent call
last)
<ipython-input-4-2b1701814572> in <module>()
11 day = int(input('Enter a day'))
12 hour = int(input('Enter hour'))
---> 13 dt = datetime.date(year, month, day, hour)
14 print("Input date: ", dt)
15 print("Corresponding Julian date: ", pyasl.jdcnv(dt))
TypeError: function takes at most 3 arguments (4 given)
You write the wrong code in line in your second example:
dt = datetime.date(year, month, day, hour)
The correct is:
dt = datetime.datetime(year, month, day, hour)

Python Length of life

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

Categories

Resources