Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7776109
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T17:47:44+00:00 2026-06-01T17:47:44+00:00

I read this and got really interested: Validating date format using regular expression so

  • 0

I read this and got really interested: Validating date format using regular expression

so I started writing my own version of the date validation function, I think I am close, but not quite, and I would like some suggestion as well as tips. I have spend a lot of time trying to tweak the function.

import re
import datetime

# Return True if the date is in the correct format
def checkDateFormat(myString):
    isDate = re.match('[0-1][0-9]\/[0-3][0-9]\/[1-2][0-9]{3}', myString)
    return isDate

# Return True if the date is real date, by real date it means,
# The date can not be 00/00/(greater than today)
# The date has to be real (13/32) is not acceptable
def checkValidDate(myString):
    # Get today's date
    today = datetime.date.today()
    myMaxYear = int(today.strftime('%Y'))

    if (myString[:2] == '00' or myString[3:5] == '00'):
        return False

    # Check if the month is between 1-12
    if (int(myString[:2]) >= 1 or int(myString[:2]) <=12):
        # Check if the day is between 1-31
        if (int(myString[3:5]) >= 1 or int(myString[3:2]) <= 31):
            # Check if the year is between 1900 to current year
            if (int(myString[-4:]) <= myMaxYear):
                return True
    else:
        return False

testString = input('Enter your date of birth in 00/00/0000 format: ')

# Making sure the values are correct
print('Month:', testString[:2])
print('Date:', testString[3:5])
print('Year:', testString[-4:])

if (checkDateFormat(testString)):
    print('Passed the format test')
    if (checkValidDate(testString)):
        print('Passed the value test too.')
    else:
        print('But you failed the value test.')
else:
    print("Failed. Try again")

Question 1: Is there other way (better) to do int(myString[3:5]) when I want to compare if it is valid? I feel my method is very repetitive, and this function must require 00/00/0000, otherwise it will break. So the function isn’t all that useful in that sense. Especially the way I handle my 00/01/1989, it is just simply comparing if they are indeed 00.

Question 2: There are many if statement, I wonder are there better way to write this test?

I would like to learn more about programming in python, any suggestion or advice will be greatly appreciated. Thank you very much.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T17:47:46+00:00Added an answer on June 1, 2026 at 5:47 pm

    Like many things in python there’s already underlying capabilities to check dates. Assuming you aren’t just doing this as an academic exercise the most straightforward way to validate a date is to try and create it.

    import datetime
    
    minyear = 1900
    maxyear = datetime.date.today().year
    
    mydate = '12/12/2000'
    dateparts = mydate.split('/')
    try:
        if len(dateparts) != 3:
           raise ValueError("Invalid date format")
        if int(dateparts[2]) > maxyear or int(dateparts[2]) < minyear:
           raise ValueError("Year out of range")
        dateobj = datetime.date(int(dateparts[2]),int(dateparts[1]),int(dateparts[0]))
    except:
        // handle errors
    

    if datetime.date is given an invalid date it will complain, eg:

    datetime.date(2000,45,23)
    
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        datetime.date(2000,45,23)
    ValueError: month must be in 1..12
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I ran Perl::Critic on one of my scripts, and got this message: Regular expression
I've got a script like this: dyski=$(df -h) while read wiersz; do i=0; for
Since I got TLDR (too long didn't read) comments, I stripped 90% of this
I read this post but I don't really understand the code... I have a
I know it is really annoying to read this topic again. Before you start
I am using Gmaps4rails. It's working really fine. But now I got an issue
I read this PHP RegEx page , but either I'm missing something, misreading something,
I read this answer and its comments and I'm curious: Are there any reasons
I read this post last night, and I noticed it was from 2006. I
I read This article and i found it interesting. To sum it up for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.