问题
I am writing a program to validate portions of an XML file. One of the points I would like to validate is a Date Time format. I've read up on the forum about using time.strptime() but the examples weren't quite working for me and were a little over my expertise. Anyone have any ideas how I could validate the following. This is the format the date and time must be in.
2/26/2009 3:00 PM
I am sure there is something built-in and very easy but I can't find. Many thanks if you've run by this before and have suggestions.
回答1:
Yes, you can use datetime.strptime():
from datetime import datetime
def validate_date(d):
try:
datetime.strptime(d, '%m/%d/%Y %I:%M %p')
return True
except ValueError:
return False
print validate_date('2/26/2009 3:00 PM') # prints True
print validate_date('2/26/2009 13:00 PM') # prints false
print validate_date('2/26/2009') # prints False
print validate_date("Should I use regex for validating dates in Python?") # prints False
回答2:
This is how you do it:
from datetime import datetime
def validate(datetime_string):
try:
return datetime.strptime(datetime_string,"%m/%d/%Y %I:%M %p")
except ValueError:
return False
回答3:
import datetime
parsed = datetime.datetime.strptime("2/26/2009 3:00 PM", r'%m/%d/%Y %H:%M %p')
iso_formatted = parsed.isoformat()
print(iso_formatted)
回答4:
You could use locale module combined with time.strptime() to ensure the date/time is in the proper order (month, day, year, etc). Or, you could do simple regex...
pattern = re.compile(r'\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2} (AM|PM)')
...I am not a regex pro lol, there's probably a better pattern.
You can also use the datetime module and create a new datetime object with the locale constant and have it convert the numbers to their proper type (day, month, year).
Good luck!
来源:https://stackoverflow.com/questions/18539266/how-to-validate-a-specific-date-and-time-format-using-python