Вводится дата в строку и надо проверить не прошли ли сроки годности
Пишу функцию, которая проверяет купоны на работоспособность. Не могу нормально сравнить дату купона нужно, чтобы первая была меньше второй:
Весь код:
def check_coupon(entered_code, correct_code, current_date, expiration_date):
value = False
entered_code = str (entered_code)
correct_code = str (correct_code)
print ( current_date.replace (",", "").split ())
print (expiration_date.replace (",", "").split ())
months = {
1 : "January" ,
2 : "February" ,
3 : "March" ,
4 : "April" ,
5 : "May" ,
6 : "June" ,
7 : "July" ,
8 : "August" ,
9 : "September",
10 : "October" ,
11 : "November" ,
12 : "December"
}
if entered_code == correct_code:
splitted_current_date = current_date.replace (",", "").split ()
splitted_expiration_date = expiration_date.replace (",", "").split ()
i = 1
while i <= 12:
if months [i] == splitted_current_date [0]: current_month = i
if months [i] == splitted_expiration_date [0]: expiration_month = i
i += 1
print (current_month )
print (expiration_month)
current_day = int (splitted_current_date [1])
expiration_day = int (splitted_expiration_date [1])
current_year = int (splitted_current_date [2])
expiration_year = int (splitted_expiration_date [2])
print (current_day)
print (expiration_day)
print (current_year)
print (expiration_year)
if current_year <= expiration_year:
if current_month <= expiration_month:
if current_day <= expiration_day:
value = True
else:
value = False
else:
value = False
return value
Вот так тестил работоспособность кода:
print (check_coupon ('123','123','September 5, 2014','October 1, 2014'), True)
print (check_coupon ('123a','123','September 5, 2014','October 1, 2014'), False)
print (check_coupon ("123", "123", "July 9, 2015", "July 9, 2015"), "==", True)
print (check_coupon ("123", "123", "July 9, 2015", "July 2, 2015"), "==", False)
Проблема в этом куске кода:
if current_year <= expiration_year:
if current_month <= expiration_month:
if current_day <= expiration_day:
value = True
Пробовал еще вот так:
if current_year <= expiration_year and current_month <= expiration_month and current_day <= expiration_day:
value = True
Ответы (2 шт):
Автор решения: CrazyElf
→ Ссылка
Условие должно быть сильно сложнее, чем то, которое вы написали. Что-то типа вот такого на псевдоязыке:
год1 < год2 или (год1 == год2 и месяц1 < месяц2) или (год1 == год2 и месяц1 == месяц2 и день1 <= день2)
Наверное, проще посчитать через некое примерное "число дней от начала эпохи" для каждой из дат и потом сравнить уже эти числа между собой:
число_дней = год * 356 + месяц * 31 + день
число_дней1 <= число_дней2
Автор решения: Serg Bocharov
→ Ссылка
Все можно значительно упростить:
from datetime import datetime
def check_coupon(entered_code, correct_code, current_date, expiration_date):
current = datetime.strptime(current_date, '%B %d, %Y')
expiration = datetime.strptime(expiration_date, '%B %d, %Y')
return entered_code == correct_code and current <= expiration
print(check_coupon(123, 123, 'September 5, 2014','October 1, 2014'))
print(check_coupon(123, 123, "July 9, 2015","July 2, 2015"))
Вывод:
True
False
UPDATE
Вот для примера, как можно преобразовывать из строки в дату:
from datetime import datetime
date_str1 = 'Monday, December 7, 2020'
date_str2 = '7/12/20'
date_str3 = '7-12-2018'
date_dt1 = datetime.strptime(date_str1, '%A, %B %d, %Y')
date_dt2 = datetime.strptime(date_str2, '%d/%m/%y')
date_dt3 = datetime.strptime(date_str3, '%d-%m-%Y')
print(date_dt1)
print(date_dt2)
print(date_dt3)
Вывод:
2020-12-07 00:00:00
2020-12-07 00:00:00
2018-12-07 00:00:00