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
#1
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.
Reply


Messages In This Thread
Date format and past date check function - by Turtle - Oct-21-2021, 07:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Exclamation Date format convert problem for SQL server eotret 5 2,000 Aug-09-2024, 07:19 AM
Last Post: Pedroski55
  Invalid Date Format fo Cached Files jland47 1 984 May-22-2024, 07:04 PM
Last Post: deanhystad
  Compare current date on calendar with date format file name Fioravanti 1 1,948 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Date Time Series Help...Please spra8560 2 1,236 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Create dual folder on different path/drive based on the date agmoraojr 2 1,327 Jan-21-2024, 10:02 AM
Last Post: snippsat
  Python date format changes to date & time 1418 4 2,607 Jan-20-2024, 04:45 AM
Last Post: 1418
  Why can't I copy and past only ONE specific tab? NewWorldRonin 8 2,803 Jan-12-2024, 06:31 PM
Last Post: deanhystad
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 2,767 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Formatting a date time string read from a csv file DosAtPython 5 4,994 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  PDF properties doesn't show created or modified date Pedroski55 4 2,555 Jun-19-2023, 08:09 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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