prgram to check number of days between starting and ending year - python

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)

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 check whether a date is in the next week, python

Basically, I'm trying to check whether a date, e.g. 2021-07-08, is in the next week, or the week after that, or neither.
#I can call the start and end dates of the current week
start = tday - timedelta(days=tday.weekday())
end = start + timedelta(days=6)
print("Today: " + str(tday))
print("Start: " + str(start))
print("End: " + str(end))
# and I can get the current week number.
curr_week = datetime.date.today().strftime("%V")
print(curr_week)
Is there a better way than getting a list of dates in curr_week + 1 and then checking whether date is in in that list?
Thanks so much
GENERAL ANSWER
It is best to stick to datetime and timedelta, since this handles all edge cases like year changes, years with 53 weeks etc.
So find the number of the next week, and compare the weeknumber of the week you want to check against that.
import datetime
# Date to check in date format:
check_date = datetime.datetime.strptime("2021-09-08", "%Y-%d-%m").date()
# Current week number:
curr_week = datetime.date.today().strftime("%V")
# number of next week
next_week = (datetime.date.today()+datetime.timedelta(weeks=1)).strftime("%V")
# number of the week after that
week_after_next_week = (datetime.date.today()+datetime.timedelta(weeks=2)).strftime("%V")
# Compare week numbers of next weeks to the week number of the date to check:
if next_week == check_date.strftime("%V"):
# Date is within next week, put code here
pass
elif week_after_next_week == check_date.strftime("%V"):
# Date is the week after next week, put code here
pass
OLD ANSWER
This messes up around year changes, and modulo doesn't fix it because there are years with 53 weeks.
You can compare the week numbers by converting them to integers. You don't need to create a list of all dates within the next week.
import datetime
# Date to check in date format:
check_date = datetime.datetime.strptime("2021-07-08", "%Y-%d-%m").date()
# Current week number, make it modulo so that the last week is week 0:
curr_week = int(datetime.date.today().strftime("%V"))
# Compare week numbers:
if curr_week == (int(check_date.strftime("%V"))-1):
# Date is within next week, put code here
pass
elif curr_week == (int(check_date.strftime("%V"))-2):
# Date is the week after next week, put code here
pass
You can cast the date you want to check in datetime, and then compare the week numbers.
# date you want to check
date = datetime.datetime.strptime("2021-07-08","%Y-%m-%d")
# current date
tday = datetime.date.today()
# compare the weeks
print(date.strftime("%V"))
print(tday.strftime("%V"))
27
32
[see Alfred's answer]
You can get the week number directly as an integer integer from the IsoCalendarDate representation of each date.
from datetime import datetime
date_format = '%Y-%m-%d'
t_now = datetime.strptime('2021-08-11', date_format)
target_date = datetime.strptime('2021-08-18', date_format)
Just using datetime comparing:
from datetime import datetime, timedelta
def in_next_week(date):
""" -1: before; 0: in; 1: after next week;"""
today = datetime.today()
this_monday = today.date() - timedelta(today.weekday())
start = this_monday + timedelta(weeks=1)
end = this_monday + timedelta(weeks=2)
return -1 if date < start else 0 if date < end else 1
Test cases:
for i in range(14):
dt = datetime.today().date() + timedelta(days=i)
print(dt, in_next_week(dt))

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 calculate the date range of first date and last date of the previous months in python

I am trying to find the first and last date of the previous five months from now using python.
today = datetime.today()
first = today.replace(day=1)
lastMonth = first - timedelta(days=153)
Now how do i find the first and last date of each of the previous five months in python?
Can anyone help me with this please?
The below is based off an two answers already on SO. It adds in the ability to respond with the first and last day over a range of dates.
Get year month for last X months
How to get the first and last day of the month
import calendar
import datetime
from dateutil.relativedelta import relativedelta
def get_last_months(start_date, months):
for i in range(months):
_, num_days = calendar.monthrange(start_date.year,start_date.month)
first_day = datetime.date(start_date.year, start_date.month, 1).strftime('%Y-%m-%d')
last_day = datetime.date(start_date.year, start_date.month, num_days).strftime('%Y-%m-%d')
yield (first_day, last_day)
start_date += relativedelta(months = -1)
months_back = 5
print([i for i in get_last_months(datetime.datetime.today(), months_back)])
Output:
[('2020-10-01', '2020-10-31'), ('2020-09-01', '2020-09-30'), ('2020-08-01', '2020-08-31'), ('2020-07-01', '2020-07-31'), ('2020-06-01', '2020-06-30')]

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