如何使用Python验证特定的日期和时间格式 [英] How to validate a specific Date and Time format using Python
本文介绍了如何使用Python验证特定的日期和时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
time.strptime()
的论坛,但是这些例子并不适合我,而且对我的专业知识稍微有些了解。任何人有任何想法,我可以验证以下。这是日期和时间的格式。 2/26/2009 3:00 PM
我相信有内置的东西,非常容易,但是我找不到。非常感谢,如果你以前运行过,并有建议。
解决方案
是的,你可以使用 datetime.strptime()
:
from datetime import datetime
$ b def validate_date(d):
try:
datetime.strptime(d,'%m /%d /%Y%I:%M%p')
返回True
,除了ValueError:
返回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')#打印False
print validate_date(我应该使用正则表达式来验证Python中的日期吗?)#打印False
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.
解决方案
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
这篇关于如何使用Python验证特定的日期和时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文