python strptime format with optional bits

后端 未结 7 670
慢半拍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 09:59

    using one regular expression and some list expressions

    time_str = "12:34.567"
    # time format is [HH:]MM:SS[.FFF]
    sum([a*b for a,b in zip(map(lambda x: int(x) if x else 0, re.match(r"(?:(\d{2}):)?(\d{2}):(\d{2})(?:\.(\d{3}))?", time_str).groups()), [3600, 60, 1, 1/1000])])
    # result = 754.567
    

提交回复
热议问题