Python Length of life - python

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

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

What date it was x amount of days ago excluding weekends in Python

As an example I want to see what the date would be if it was today - 6 days. However, I only want to count days that are weekdays. So given 8/22 the output should be 8/12 as that is 6 business days only.
Tried using the weekday function to return if it is a 5 or 6 for saturday and sunday and skipping those days but I am not having luck so far
Current code:
from datetime import datetime, timedelta
age = 6
counter = 0
difference = datetime.today() - timedelta(counter)
while counter <= age:
difference = datetime.today() - timedelta(counter)
counter = counter + 1
this code only returns the day with the weekends included as I haven't been able to figure out how to exclude the weekend. I set up the code to loop to check if it is a 5 or 6 using the weekday() function but I keep getting bad results when attempting that
from datetime import date, timedelta
def weekdays_between(startdate,stopdate):
day = startdate
daycount = 0
while day < stopdate :
if day.weekday() < 5 :
daycount += 1
day = day + timedelta(days=1)
return daycount
if __name__ == "__main__" :
day=date.today()
dayn=day + timedelta(days=45)
print(weekdays_between(day,dayn))
You can calculate the actual days difference by calculating the number of weekends past, and subtracting the date by the days difference and the days in weekend to get the result.
from datetime import datetime,timedelta
from math import ceil
def subtract_weekdays (from_date, diff):
no_of_weekends = ceil((diff - from_date.weekday())/5)
result_date = from_date - timedelta(days=diff + no_of_weekends * 2)
return result_date
print(subtract_weekdays(datetime.today(), 6))

prgram to check number of days between starting and ending year

i am trying to write a program where I need the user to input a starting year and ending year and then the program calculates the number of days between the years. I have tried to attempt this and am a little stuck. I am required to also work out if the time includes leap years aswell.
if anyone is able to help me out would be appreciated.
The output should be as follows :
Year 1 :1980
Year 2: 2022
Number of days : 15706
import datetime
firstDate = input("Year 1?")
secondDate = input("Year 2?")
firstDateObj = datetime.datetime.strptime(firstDate, "%Y-%m-%d")
secondDateObj = datetime.datetime.strptime(secondDate, "%Y-%m-%d")
totalDays = (firstDateObj – secondDateObj).days
print(totalDays, "Day(s)")
except ValueError as e:
print(e)
thanks
Try using the datetime.date method:
Using this method you can just take the first of January of each year:
from datetime import date
first_year = input("Year 1? ")
second_year = input("Year 2? ")
first_date = date(int(first_year), 1, 1)
second_date = date(int(second_year), 1, 1)
Subtracting these elements returns a datetime.timedelta object -
between_days = second_date - first_date
print(between_days.days)

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

Displaying age in seconds using Python3

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.

Categories

Resources