带有可选位的python strptime格式 [英] python strptime format with optional bits
本文介绍了带有可选位的python strptime格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我有:
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
除非我要转换一个没有微秒的字符串。如何指定微秒是可选的(如果它们不在字符串中,则应将其视为0)?
This works great unless I'm converting a string that doesn't have the microseconds. How can I specify that the microseconds are optional (and should be considered 0 if they aren't in the string)?
推荐答案
您可以使用 try / except
块:
try:
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
这篇关于带有可选位的python strptime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文