views:

31

answers:

2

I wanted to check if user has entered the input in particular order or not. Basically i wanted user to input date in format like this

%d/%m/%y %H:%M

Is there any way i can compare string input with the above format in python?

+2  A: 

This sounds like a job for... Regular Expressions! Have a look at the re module. What you want is simple enough that it would be fairly trivial to just hand you the regex for it, but you should learn to use them yourself.

OK, for this job, the strptime answer is better. But for the general case of making sure a string matches up with a format, regular expressions are generally the way to go.

Omnifarious
Thanks Omnifarious.
itsaboutcode
Yes, the regex for valid dates would be pretty bad and depend on what format you wanted to allow. `strptime` is a lot more flexible for a lot less code (on our part)
Wayne Werner
+6  A: 
import time
time.strptime("01/01/09 12:23", "%d/%m/%y %H:%M")

This will raise ValueError if the string doesn't match:

time.strptime("01/01/09 12:234", "%d/%m/%y %H:%M")
time.strptime("01-01-09 12:23", "%d/%m/%y %H:%M")

By the way, please don't bring back two-digit years--use %Y if at all possible.

Glenn Maynard
Your method works too, I suppose. *sigh* In fact, it's likely better than mine for this particular purpose.
Omnifarious
Thanks Glenn, really appreciate that.
itsaboutcode