Search code examples
pythonpython-2.7strptime

How to parse times that may or may not have decimal seconds in Python (2.7)?


How can I have strptime optionally use the decimal seconds when parsing? I'm looking for a concise way to parse both %Y%m%d-%H:%M:%S.%f and %Y%m%d-%H:%M:%S.

With the %f I recive error:

ValueError: time data '20130807-13:42:07' does not match format '%Y%m%d-%H:%M:%S.%f'

Solution

  • t = t.rsplit('.', 1)[0]
    time.strptime('%Y%m%d-%H:%M:%S.%f', t)
    

    Or just make sure to add a decimal:

    if not '.' in t:
        t += '.0'
    time.strptime('%Y%m%d-%H:%M:%S.%f', t)
    

    This should do it.