在python中解析可以采用多种格式的日期 [英] Parsing a date that can be in several formats in python
问题描述
我想解析一个可以采用多种格式的日期,这是我事先知道的.如果我无法解析,我会返回 nil.在 ruby 中,我喜欢这样:
I would like to parse a date that can come in several formats, that I know beforehand. If I could not parse, I return nil. In ruby, I do like this:
DATE_FORMATS = ['%m/%d/%Y %I:%M:%S %p', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M', '%m/%d/%Y', '%Y/%m/%d']
def parse_or_nil(date_str)
parsed_date = nil
DATE_FORMATS.each do |f|
parsed_date ||= DateTime.strptime(date_str, f) rescue nil
end
parsed_date
end
这是简洁且有效的.我如何在 Python 中做同样的事情?
This is concise and works. How can I do the same thing in Python?
推荐答案
您可以使用 try/except
来捕获尝试使用非- 匹配格式.正如@Bakuriu 提到的,您可以在找到匹配项时停止迭代以避免不必要的解析,然后在 my_date
由于找到不匹配的格式而未定义时定义您的行为:
You can use try/except
to catch the ValueError
that would occur when trying to use a non-matching format. As @Bakuriu mentions, you can stop the iteration when you find a match to avoid the unnecessary parsing, and then define your behavior when my_date
doesn't get defined because not matching formats are found:
您可以使用 try/except
来捕获尝试使用不匹配格式时会发生的 ValueError
:
You can use try/except
to catch the ValueError
that would occur when trying to use a non-matching format:
from datetime import datetime
DATE_FORMATS = ['%m/%d/%Y %I:%M:%S %p', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M', '%m/%d/%Y', '%Y/%m/%d']
test_date = '2012/1/1 12:32:11'
for date_format in DATE_FORMATS:
try:
my_date = datetime.strptime(test_date, date_format)
except ValueError:
pass
else:
break
else:
my_date = None
print my_date # 2012-01-01 12:32:11
print type(my_date) # <type 'datetime.datetime'>
这篇关于在python中解析可以采用多种格式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!