Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

Check Date Format from a Python Tkinter entry widget

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...