0

I have tried to use the datetime code but i really don't understand it very much. I have managed to allow the user to input a date but i am not quite sure how to compare the dates. Here is what i have so far.

from datetime import datetime
now = datetime.now()

import re

validDate = False
while not validDate:
    cdate = input("please enter your card expiration date: ")

    if (re.match("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", cdate)):
        print("Valid")
        validDate = True
    else:
        print("Error. Enter date in format dd/mm/yyyy")

I really have no clue how to compare the two please help me. if you have any suggestions for code that might be on this site please tell me. In the meantime i will keep trying to research.

  • 1
    Possible duplicate of [How to compare two dates?](https://stackoverflow.com/questions/8142364/how-to-compare-two-dates) – GPhilo Feb 06 '18 at 09:23
  • i have looked at how to compare two dates and tried the code but it has not worked for me, – darius DEAnzo Feb 06 '18 at 09:38
  • Please update your question with the code you tried then. In your sample code there is no comparison yet. – GPhilo Feb 06 '18 at 09:40

2 Answers2

0

you can try this one :

 from datetime import datetime, date
 datet = input("please enter your card expiration date: ")

 ExpirationDate = datetime.strptime(datet,"%Y-%m-%d").date()
 now = date.today()
 if ExpirationDate < now:
      print("expired")

for your second condition you can use ExpirationDate.year for the year of entered date and now.year for current year. With that you can write condition according to your need .

 if ExpirationDate.year > now.year+1:
      print("date not accepted")
 elif ExpirationDate < now :
      print("expired")
 else :
      print("valid ")

remaining all code is same

UPDATE :

from datetime import datetime, date

while True:
    datet = input("please enter your card expiration date: ")
    ExpirationDate = datetime.strptime(datet, "%Y-%m-%d").date()
    now = date.today()
    if ExpirationDate.year > now.year + 1:
         print("date not accepted")
         continue
    elif ExpirationDate < now:
         print("expired")
         continue
    else:
         print("valid ")
         break

it will again ask to enter date if date not accpted or expired

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
0

In your case, you should use calendar.

yann
  • 652
  • 7
  • 14