Python daysBetweenDate - python

I think I might have an infinite loop because I keep getting back an error message whenever I run the code, it says "program shut down for using 13 CPU seconds."
The entire code, should take a date as input and output the next day, this code assumes all months are 30 days. Aside from the daysBetweenDates function, everything else seems to be working fine. Does anyone have any suggestions? Or maybe someone can tell me what I'm missing?
def daysInMonth(year, month):
return 30
def nextDay(year, month, day):
if day < 30:
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
return
def dateIsBefore(year1, month1, day1, year2, month2, day2):
if year1 < year2:
return True
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
days = 0
while dateIsBefore(year1, month1, day1, year2, month2, day2):
days += 1
return days
def test():
test_cases = [((2012,1,1,2012,2,28), 58),
((2012,1,1,2012,3,1), 60),
((2011,6,30,2012,6,30), 366),
((2011,1,1,2012,8,8), 585 ),
((1900,1,1,1999,12,31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
print result
else:
print "Test case passed!"
test()

Your daysBetweenDates() algorithm does indeed have an infinite loop.
while dateIsBefore(year1, month1, day1, year2, month2, day2):
days += 1
You never modify any of the year/month/day values here in the loop, so if the condition is true once, it will be true forever.
The solution, in concept, would be to decrease day2 by one every time, so when the two dates become equal, days will be the day difference between them. However, since you said you made the assumption that each month has 30 days, you're overcomplicating things for yourself. You can find the day difference between two dates by converting the (year, month, day) tuple to a day value. For example,
def days_between_dates(y1, m1, d1, y2, m2, d2):
date1 = y1*360 + (m1-1)*30 + d1
date2 = y2*360 + (m2-1)*30 + d2
# assuming you want to return 0 if date2 is before date1
return date2 - date1 if date2 >= date1 else 0

This solution counts daysInMonth correctly, doesn't involve any kind of infinite loop, counts correct dates in a leap year and provides an exact answer to inputs.
The solution is written in Python.
def daysInMonth(m,y):
if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m ==10 or m == 12:
return 31
else :
if m == 2:
if isLeapYear(y):
return 29
return 28
return 30
def nextDay(y,m,d):
if d < daysInMonth(m,y):
return y, m, d+1
else:
if m == 12:
return y + 1, 1, 1
else:
return y, m + 1, 1
def isLeapYear(y):
if y % 400 == 0:
return True
elif y % 4 == 0:
return True
else:
if y % 100 == 0:
return False
return False
def dateIsBefore(y1, m1, d1, y2, m2, d2):
days = 0
if y1 < y2 :
return True
if y1 == y2:
if m1 < m2:
return True
if m1 == m2:
return d1<d2
return False
def daysbetweendates(y1, m1, d1, y2, m2, d2):
days = 0
while dateIsBefore(y1, m1, d1, y2, m2, d2):
y1, m1, d1 = nextDay(y1, m1, d1)
days = days + 1
return days
def test():
test_cases = [((2012,1,1,2012,2,28), 58),
((2012,1,1,2012,3,1), 60),
((2011,6,30,2012,6,30), 366),
((2011,1,1,2012,8,8), 585 ),
((1900,1,1,1999,12,31), 36523)]
for (args, answer) in test_cases:
result = daysbetweendates(*args)
if result != answer:
print "Test with data:", args, "failed"
print result
else:
print "Test case passed!"
test()

The function dateIsBefore is incomplete.
def dateIsBefore(year1, month1, day1, year2, month2, day2):
if year1 < year2:
return True
if year1 == year2 and month1 < month2:
return True
if year1 == year2 and month1 == month2 and day1 < day2:
return True
return False
(It could be simplified, but I left it like this for clarity. Also, of course, you could use datetime.date--someone else already made that comment; see also other answer that tells you to increment year1,month1, and day1)

dateIsBefore will always return True.

Related

count the number of days between two dates

I am counting number of days between two dates.For first testcase output is wrong 10108
expected output 10109
In first test case 1 day is missing in output
from typing import*
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
d1 = self.days(int(date1[:4]),int(date1[5:7]),int(date1[8:]))
d2 = self.days(int(date2[:4]),int(date2[5:7]),int(date2[8:]))
return abs(d2-d1)
def isLeap (self, N):
if N % 400 == 0:
return True
if N % 100 == 0:
return False
if N % 4 != 0:
return False
return True
def days(self, year,month,rem_days):
months_list = [31,28,31,30,31,30,31,31,30,31,30,31]
days_count = 0
for i in range(1971,2101):
if year > i:
if self.isLeap(i):
days_count += 366
else:
days_count += 365
else:
break
if self.isLeap(year) and month > 2:
days_count += 1
for j in range(1,month):
if month > j:
days_count += months_list[j]
return days_count + rem_days
vals = Solution()
print(vals.daysBetweenDates("2010-09-12","1983-01-08"))
print(vals.daysBetweenDates("2019-06-29", "2019-06-30"))
print(vals.daysBetweenDates("2020-01-15", "2019-12-31"))
The month starts at one, you get the number of days for each month from the wrong index (1 for January when the correct index is 0...). Subtract one when you look up the days for each month
for j in range(1, month):
days_count += months_list[j - 1]

How to check given date is exactly a month ago : python

I need to check if a given date is exactly a month ago from today, for example, if today is 01-Nov-2021 then exactly a month ago will be 01-Oct-2021 (not exactly 30 days.)
I wrote a code and it works fine
today = fields.Date.from_string(fields.Date.today())
if today.month == 1:
one_month_ago = today.replace(year=today.year - 1, month=12)
else:
extra_days = 0
while True:
try:
one_month_ago = today.replace(month=today.month - 1, day=today.day -
extra_days)
break
except ValueError:
extra_days += 1
if one_month_ago == given_date:
# do something
else:
# do something
It handles well mostly all the cases but mishandles some cases. For example, the given date is 31-March-2021 and today date is 30-April-2021 and 31-April-2021 will not come to compare. I need my code to run daily and check something. It also mishandles cases of 29-31 January because 29-31 February will not come to compare.
From the given date, you can find the previous month and year and using these two obtained values, find the length of the previous month. The last thing to be done will be to compare the day of the given date with the length of the previous month and accordingly, return the desired date.
Demo:
from datetime import date
from calendar import monthrange
def date_a_month_ago(today):
x = today.month - 1
previous_month = 12 if x == 0 else x
year = today.year - 1 if x == 0 else today.year
last_day_of_previous_month = monthrange(year, previous_month)[1]
day = last_day_of_previous_month if today.day > last_day_of_previous_month else today.day
return date(year, previous_month, day)
# Tests
print(date_a_month_ago(date(2021, 11, 1)))
print(date_a_month_ago(date(2021, 1, 31)))
print(date_a_month_ago(date(2021, 12, 31)))
print(date_a_month_ago(date(2021, 3, 29)))
print(date_a_month_ago(date(2020, 3, 29)))
print(date_a_month_ago(date(2021, 3, 30)))
print(date_a_month_ago(date(2020, 3, 30)))
Output:
2021-10-01
2020-12-31
2021-11-30
2021-02-28
2020-02-29
2021-02-28
2020-02-29
ONLINE DEMO
May be like this:
from typing import Tuple
def last_month(year: int, month: int) -> Tuple[int, int]:
y, m = year, month - 1
if m == 0:
y, m = y - 1, 12
return y, m
def one_month_ago(today: datetime) -> datetime:
y, m = last_month(today.year, today.month)
dt = today.replace(year=y, month=m)
for day in range(today.day, 0, -1):
try:
return dt.replace(day=day)
except ValueError:
...
I did this and it's giving me the required output:
from datetime import date
from calendar import monthrange
def is_one_month(given_date, today):
x = today.month - 1
previous_month = 12 if x == 0 else x
year = today.year - 1 if x == 0 else today.year
last_day_of_previous_month = monthrange(year, previous_month)[1]
day = last_day_of_previous_month if today.day > last_day_of_previous_month else today.day
one_month_ago = date(year, previous_month, day)
if today.month == 2:
if given_date.month == today.month-1 and given_date.year == today.year and given_date.day >= 28:
return 'it is one month before'
if today.month == 4 or today.month == 6 or today.month == 9 or today.month == 11:
if given_date.month == today.month-1 and given_date.day == 31:
return 'it is one month before'
if one_month_ago == given_date:
return 'it is one month before'
else:
return 'it is NOT one month before'
print(is_one_month(date(2021, 1, 30), date(2021, 2, 28)))
Output:
it is one month before

How to compare dates (in string)?

I want to determine the cost by specific rules between two dates. The problem is that the input is in not in a date format but as:
6 6 2020
9 9 2020
The conditions are as follows:
If same day, there is a fixed cost of 20.
If after a day but still within a month cost = 30 * (the number of days).
If after a month but still within a year, the cost = 1000 * (the number of months).
If after a year in which it was created,then there is a fixed cost of 20000.
How do I compare them by changing only the cost( ) ?
what I have tried is far from perfect and already uses too many branches:
def cost(d1, m1, y1, d2, m2, y2):
yd=0
md=0
dd = 0
if (y1==y2):
yd=0
else: yd=abs(y1-y2)
if (m1==m2):
md=0
else: md=abs(m1-m2)
if (d1==d2):
dd=0
else: dd=abs(d1-d2)
cost = int()
if (md>11 or yd>0):
cost = 20000
elif (md>0 and md<12):
cost = 1000*md
elif (dd==0 and md==0 and yd==0):
cost = 20
elif (dd>0 and md==0 and yd==0):
cost = dd*30
print("yd=",yd)
print("md=",md)
print("dd=",dd)
return cost
if __name__ == '__main__':
#d1M1Y1 = input().split()
d1M1Y1 = [6,1,2020]
d1 = int(d1M1Y1[0])
m1 = int(d1M1Y1[1])
y1 = int(d1M1Y1[2])
#d2M2Y2 = input().split()
d2M2Y2 = [4,1,2021]
d2 = int(d2M2Y2[0])
m2 = int(d2M2Y2[1])
y2 = int(d2M2Y2[2])
result = server_cost(d1, m1, y1, d2, m2, y2)
print(str(result) + '\n')
import datetime
def cost(d1, m1, y1, d2, m2, y2):
date1 = datetime.datetime(y1, m1, d1)
date2 = datetime.datetime(y2, m2, d2)
delta = date2 - date1
if delta.days <= 1:
return 20
elif delta.days < 30:
return 30 * delta.days
elif delta.days < 365:
return 1000 * (delta.days//12) # use a function that suits your def of months
else:
return 20000
As mentioned in comment, best to convert to datetime
E.g.
import datetime
d1M1Y1 = [6,1,2020]
d1 = int(d1M1Y1[0])
m1 = int(d1M1Y1[1])
y1 = int(d1M1Y1[2])
#d2M2Y2 = input().split()
d2M2Y2 = [4,1,2021]
d2 = int(d2M2Y2[0])
m2 = int(d2M2Y2[1])
y2 = int(d2M2Y2[2])
date1 = datetime.datetime(y1, m1, d1)
date2 = datetime.datetime(y2, m2, d2)
print(date1)
print(date2)
EDIT: Demo for working with datetime differences
dateTimeDifference = date2 - date1
# Datedifferene in days
daysDifference = dateTimeDifference.total_seconds() / 86400
print(daysDifference)
if daysDifference > 365:
print ("More than a year")
else:
print("Less than a year")
import time
import datetime
def str_to_date(str):
fmt = '%d %m %Y'
time_tuple = time.strptime(str, fmt)
day, month, year = time_tuple[:3]
a_date = datetime.date(day, month, year)
return a_date
a = str_to_date('22 7 2020')
b = str_to_date('5 8 2019')
c = abs(a-b)
if c.days<=1:
cost=20
elif c.days<30:
cost=30*c.days
elif c.days<365:
cost=1000*(c.days//30)
else:
cost=20000
print(cost)

Calculating days between dates in Python?

Got set some course homework to do this. It was going all good until I noticed one of the test cases werent working, trying to get the days between 2012-1-1 and 2013-1-1.
I guessed it would be 366, extra day as 2012 was a leap year. This code seems to be guessing 365, my tutor has marked the answer down as 360.
He said something about "just make all months 30 days", so I'm thinking his 360 is something related to that? Anyway, that doesn't excuse my code guessing 365 when it should be guessing 366.
Output is as shows
Test case passed! CONGRATULATIONS
Test with data: (2012, 1, 1, 2013, 1, 1) failed passed 365 should of passed 360
Test case passed! CONGRATULATIONS
daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def get_days_from_year(year):
days = year * 365
i = 0
while i < year:
i += 1
if is_leap_year(i):
days += 1
return days
def get_days_from_month(month, year):
days = 0
i = 0
while i < month:
if i == 1 and is_leap_year(year):
days += daysOfMonths[i] + 1
else:
days += daysOfMonths[i]
i += 1
return days
def get_days_from_date(year, month, day):
days_in_year = get_days_from_year(year)
days_in_month = get_days_from_month(month - 1, year)
days = days_in_year + days_in_month + day
return days
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
first_date_days = get_days_from_date(year1, month1, day1)
second_date_days = get_days_from_date(year2, month2, day2)
if first_date_days > second_date_days:
return first_date_days - second_date_days
else:
return second_date_days - first_date_days
def test():
test_cases = [((2012,9,30,2012,10,30),30),
((2012,1,1,2013,1,1),360),
((2012,9,1,2012,9,4),3)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print("Test with data:", args, "failed passed", result, "should of passed", answer)
else:
print("Test case passed! CONGRATULATIONS")
test()
You are incrementing i in the wrong place. You have:
while i < year:
i += 1
if is_leap_year(i):
days += 1
but should be:
while i < year:
if is_leap_year(i):
days += 1
i += 1
because of this, your leap years are all off by 1 (2011 vs 2012, 2015 vs 2016, etc.)
He said something about "just make all months 30 days", so
def get_range(year1,month1,day1,year2,month2,day2):
"""
assumes all months have 30 days, with no leap years
~ for some weird reason i dont understand
(probably so you dont use builtin datetime)
"""
days_difference = (year2-year1)*360
days_difference += (month2-month1)*30
return days_difference + day2-day1
print(get_range(2012, 1, 1, 2013, 1, 1))
if you want to get the actual number of days between two dates
from datetime import datetime
def get_real_range(year1,month1,day1,year2,month2,day2):
return (datetime(year2,month2,day2) - datetime(year1,month1,day1)).days

Not defined method [duplicate]

This question already has answers here:
Why does this python method gives an error saying global name not defined?
(3 answers)
Closed 4 years ago.
below is my code (all the methods are indented in original), after running that code I get this error:
NameError: global name 'checkDate' is not defined
the method are defined so i don't know whats the issue here (the code was in Java and work well there I just did the modification for this to work in python)
class Date:
def __init__(self, *args):
if len(args) == 3:
self._day, self._month, self._year = args
elif len(args) == 1:
self._day = args[0]._day
self._month = args[0]._month
self._year = args[0]._year
else:
raise TypeError("wrong number of arguments to Date constructor")
# methods
# checkDate - Check if the date is valid
def checkDate (self, day, month, year):
if year > 0 and month > 0 and month < 13 and day > 0 and day < 32:
if month == 1 or 3 or 5 or 7 or 8 or 10 or 12: return True
if month == 4 or 6 or 9 or 11:
if day == 31: return False
return True
if month == 2:
if (month % 4 == 0 and (month % 100 != 0 or (month % 100 == 0 and month % 400 == 0))):
if day > 28: return False
elif day > 27: return False
return False
# calculateDate - Computes the day number since the beginning of the Christian counting of years.
def calculateDate (self, day, month, year):
if month < 3:
year -= 1
month = month + 12
return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62);
# getDay - Return the day
def getDay(self): return self._day
# getMonth - Return the month
def getMonth(self): return self._month
# getYear - Return the year
def getYear(self): return self._year
# setDay - Sets the day (only if date remains valid)
def setDay(self, dayToSet):
if checkDate(dayToSet,_month,_year): _day = dayToSet
# setMonth - Sets the month (only if date remains valid)
def setMonth (self, monthToSet):
if checkDate(_day,monthToSet,_year): _month = monthToSet
# setYear - sets the year (only if date remains valid)
def setYear(self, yearToSet):
if checkDate(_day,_month,yearToSet): _year = yearToSet
def main():
birthDate = Date(1,1,2000)
print(birthDate.getDay())
print(birthDate.getMonth())
print(birthDate.getYear())
birthDate.setDay(8)
birthDate.setMonth(8)
birthDate.setYear(1987)
print(birthDate.getDay())
print(birthDate.getMonth())
print(birthDate.getYear())
if __name__ == "__main__": main()
You need to do self.checkDate() since checkDate is a method of your Date class.
Additionally, in setDay(), setMonth() and setYear() the variables being assigned to (_day, _month, and _year respectively) need a self. before them as well.

Categories