Adam
Adam

Reputation: 3795

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'

Upvotes: 1

Views: 318

Answers (2)

Torxed
Torxed

Reputation: 23490

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.

Upvotes: 2

user1786283
user1786283

Reputation:

Try something like this:

import time

def timeFormatCheck(input):
    try:
        output = time.strptime(input, '%Y%m%d-%H:%M:%S.%f') #or you could even return
    except ValueError:
        output = time.strptime(input,'%Y%m%d-%H:%M:%S') #or you could even return
    return output

Or if you want a boolean value, try this:

import time

def isDecimal(input):
    try:
        time.strptime(input, '%Y%m%d-%H:%M:%S.%f')
        return True
    except ValueError:
        return False

Upvotes: 2

Related Questions