python strptime format with optional bits

后端 未结 7 667
慢半拍i
慢半拍i 2020-12-03 09:51

Right now I have:

timestamp = datetime.strptime(date_string, \'%Y-%m-%d %H:%M:%S.%f\')

This works great unless I\'m converting a string tha

相关标签:
7条回答
  • 2020-12-03 10:19
    datetime(*map(int, re.findall('\d+', date_string)))
    

    can parse both '%Y-%m-%d %H:%M:%S.%f' and '%Y-%m-%d %H:%M:%S'. It is too permissive if your input is not filtered.

    It is quick-and-dirty but sometimes strptime() is too slow. It can be used if you know that the input has the expected date format.

    0 讨论(0)
提交回复
热议问题