Python Forum
Date format and past date check function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Date format and past date check function
#6
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())
Reply


Messages In This Thread
RE: Date format and past date check function - by deanhystad - Oct-22-2021, 09:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 281 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Date Time Series Help...Please spra8560 2 406 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Create dual folder on different path/drive based on the date agmoraojr 2 478 Jan-21-2024, 10:02 AM
Last Post: snippsat
  Python date format changes to date & time 1418 4 667 Jan-20-2024, 04:45 AM
Last Post: 1418
  Why can't I copy and past only ONE specific tab? NewWorldRonin 8 893 Jan-12-2024, 06:31 PM
Last Post: deanhystad
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,087 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Formatting a date time string read from a csv file DosAtPython 5 1,376 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  PDF properties doesn't show created or modified date Pedroski55 4 1,130 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  How should I run pip-date in python3? newbieAuggie2019 5 1,955 Mar-31-2023, 03:21 PM
Last Post: snippsat
  How to see the date of installation of python modules. newbieAuggie2019 4 1,671 Mar-31-2023, 12:40 PM
Last Post: newbieAuggie2019

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020