Pergunta

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'
Foi útil?

Solução

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.

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top