問題描述
我正在編寫一個程序來驗證 XML 文件的某些部分.我要驗證的要點之一是日期時間格式.我已經在論壇上閱讀了有關使用 time.strptime()
的信息,但是這些示例對我來說不太適用,并且超出了我的專業知識.任何人都知道如何驗證以下內容.這是日期和時間必須采用的格式.
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.
推薦答案
是的,你可以使用 datetime.strptime()
:
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 驗證特定的日期和時間格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!