I'm looking to combine my logic into a single function to check if the user's input is in my required format and to make sure the date is not in the past. Every time I think about it, it seems like I'm just a step away or there is a very simple solution but I've been stewing over this all day without any success.
Here's what I have so far:
from datetime import datetime
user_date = input("Provide date: ")
valid = False
while not valid:
try:
date = datetime.strptime(
user_date, "%m/%d/%Y").strftime("%m/%d/%Y")
valid = True
except ValueError:
user_date = input("Incorrect date format. Please try again: ")
I also have this snippet but am at a lose for how to incorporate it:
past = datetime.strptime(user_date, "%m/%d/%Y")
present = datetime.now()
if past.date() < present.date():
return True
else:
return False
I was thinking I could just put the past date check after the valid format check however if it fails the second check, I need to go back and make sure that their new input is in the valid format again.
As a bonus, I'm taking the time in a different input so if someone can help me take it as one input, that'd be great too.
just compare them
from datetime import datetime
#make present date in to string(year/month/day):
present=datetime.now().strftime("%Y/%m/%d")
#split the date into presentlist as int:
presentlist=list(map(int,present.split('/')))
#print(presentlist)
#after the user input the date and checked by your code, it should be a string, so you split them again
userdate='2000/05/19'
userdatelist=list(map(int,userdate.split('/')))
#and you compare:
isPast=False
for num in range(len(presentlist)):
if userdatelist[num]<presentdatelist[num]:
isPast=True
break
else:
continue
print(isPast)
from datetime import datetime
def enter_date():
'''Enter date string. Return reformatted datestring and flag indicating if date is in the past'''
while True:
date = input('Provide date: ')
try:
date = datetime.strptime(date, '%m/%d/%Y')
except ValueError as msg:
print(msg)
else:
return date.strftime('%m/%d/%Y'), date < datetime.now()
print(enter_date())
import datetime
class DateFormatError(Exception):
pass
class PastDateError(Exception):
pass
def validate_date(date: str) -> datetime.datetime:
try:
date_time = datetime.datetime.strptime(date, "%m/%d/%Y %H:%M:%S")
except ValueError:
raise DateFormatError
if date_time.date() < datetime.date.today():
raise PastDateError
return date_time
def main():
while True:
user_date = input("Provide date: ")
try:
date_time = validate_date(user_date)
break
except DateFormatError:
print("Incorrect date format. Please try again")
except PastDateError:
print("Dates in the past are not allowed. Please try again")
print(f"Correct date recieved {date_time}")
if __name__ == "__main__":
main()
(Oct-21-2021, 10:41 PM)deanhystad Wrote: [ -> ]from datetime import datetime
def enter_date():
'''Enter date string. Return reformatted datestring and flag indicating if date is in the past'''
while True:
date = input('Provide date: ')
try:
date = datetime.strptime(date, '%m/%d/%Y')
except ValueError as msg:
print(msg)
else:
return date.strftime('%m/%d/%Y'), date < datetime.now()
print(enter_date())
Thanks for this. It helped me achieve my goal but I did tweak it a bit. I added it so that if the date was in the past, it would not exit the while loop so that the user had to enter in a date that was either today or in the future.
from datetime import datetime
def enter_date():
'''Enter date string. Return reformatted datestring and flag indicating if date is in the past'''
while True:
date = input('Provide date: ')
try:
date = datetime.strptime(date, '%m/%d/%Y')
except ValueError:
print("Incorrect date format, please enter a proper date.")
else:
present = datetime.now()
if date.date() >= present.date():
return date.strftime('%m/%d/%Y')
else:
print("Date must not be in the past.")
print(enter_date())
Output:
Provide date: 912
Incorrect date format, please enter a proper date.
Provide date: 101010
Incorrect date format, please enter a proper date.
Provide date: 10/20/2021
Date must not be in the past.
Provide date: 1021
Incorrect date format, please enter a proper date.
Provide date: 10/21/2021
10/21/2021
You can shorten it up a bit more. There's no need for the "present" variable of the final "else". It is also a good idea to provide guidance on what is the proper date format.
from datetime import datetime
def enter_date(prompt, valid):
'''Enter date string. Return reformatted datestring and flag indicating if date is in the past'''
while True:
date = input('Provide date (m/d/yyyy): ')
try:
date = datetime.strptime(date, '%m/%d/%Y')
except ValueError:
print("Incorrect date format, please enter a proper date.")
else:
if date.date() >= datetime.now().date():
return date.strftime('%m/%d/%Y')
print("Date must not be in the past.")
print(enter_date())