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
#4
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()
Turtle likes this post
Reply


Messages In This Thread
RE: Date format and past date check function - by Yoriz - Oct-22-2021, 12:17 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Invalid Date Format fo Cached Files jland47 1 167 May-22-2024, 07:04 PM
Last Post: deanhystad
  Compare current date on calendar with date format file name Fioravanti 1 342 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Date Time Series Help...Please spra8560 2 454 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Create dual folder on different path/drive based on the date agmoraojr 2 540 Jan-21-2024, 10:02 AM
Last Post: snippsat
  Python date format changes to date & time 1418 4 758 Jan-20-2024, 04:45 AM
Last Post: 1418
  Why can't I copy and past only ONE specific tab? NewWorldRonin 8 993 Jan-12-2024, 06:31 PM
Last Post: deanhystad
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,188 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Formatting a date time string read from a csv file DosAtPython 5 1,500 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  PDF properties doesn't show created or modified date Pedroski55 4 1,195 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  How should I run pip-date in python3? newbieAuggie2019 5 2,066 Mar-31-2023, 03:21 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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