python strptime format with optional bits

后端 未结 7 666
慢半拍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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2020-12-03 10:02

    For my similar problem using jq I used the following:

    |split("Z")[0]|split(".")[0]|strptime("%Y-%m-%dT%H:%M:%S")|mktime
    

    As the solution to sort my list by time properly.

    0 讨论(0)
  • 2020-12-03 10:05

    I'm late to the party but I found if you don't care about the optional bits this will lop off the .%f for you.

    datestring.split('.')[0]

    0 讨论(0)
  • 2020-12-03 10:12

    What about just appending it if it doesn't exist?

    if '.' not in date_string:
        date_string = date_string + '.0'
    
    timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
    
    0 讨论(0)
提交回复
热议问题