Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Using a Tkinter input box, I ask a user for a date in the format YYYYMMDD. I would like to check if the date has been entered in the correct format , otherwise raise an error box. The following function checks for an integer but just need some help on the next step i.e the date format.

    def retrieve_inputBoxes():
        startdate = self.e1.get()  # gets the startdate value from input box
        enddate = self.e2.get()    # gets the enddate value from input box
        if startdate.isdigit() and enddate.isdigit():
           pass
        else:
            tkinter.messagebox.showerror('Error Message', 'Integer Please!')
            return     
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

The easiest way would probably be to employ regex. However, YYYYMMDD is apparently an uncommon format and the regex I found was complicated. Here's an example of a regex for matching the format YYYY-MM-DD:

import re

text = input('Input a date (YYYY-MM-DD): ')
pattern = r'(19|20)dd[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])'
match = re.search(pattern, text)
if match:
    print(match.group())
else:
    print('Wrong format')

This regex will work for the twentieth and twentyfirst centuries and will not care how many days are in each month, just that the maximum is 31.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...