python strptime format with optional bits

后端 未结 7 669
慢半拍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:01

    You could use a try/except block:

    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')
    

提交回复
热议问题