问题描述
我想解析一下有几种格式的日期,我事先知道。如果我无法解析,我返回零。在红宝石中,我喜欢这样:
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
来捕获尝试使用非匹配格式时会发生的 ValueError
。 @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中的几种格式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!