python strptime format with optional bits

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

    I prefer using regex matches instead of try and except. This allows for many fallbacks of acceptable formats.

    # full timestamp with milliseconds
    match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z", date_string)
    if match:
        return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ")
    
    # timestamp missing milliseconds
    match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", date_string)
    if match:
        return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%SZ")
    
    # timestamp missing milliseconds & seconds
    match = re.match(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z", date_string)
    if match:
        return datetime.strptime(date_string, "%Y-%m-%dT%H:%MZ")
    
    # unknown timestamp format
    return false
    

    Don't forget to import "re" as well as "datetime" for this method.

提交回复
热议问题