datetime.time() class - How to pass it a time string?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jul 24 21:45:51 EDT 2007


En Tue, 24 Jul 2007 14:37:20 -0300, Miles <semanticist at gmail.com> escribió:

> On 7/24/07, Robert Dailey wrote:

>> I have a string in the following format:
>>
>> "00:00:25.886411"
>>
>> I would like to pass this string into the datetime.time() class and
>> have it parse the string and use the values. However, the __init__()
>> method only takes integers (which means I'd be forced to parse the
>> string myself). Does anyone know of a way I can make it use the
>> string? Thanks.
>
> timestr = "00:00:25.886411"
> timesep = re.compile('[:.]')
> datetime.time(*[int(i) for i in timesep.split(timestr)])

That's OK if one can always guarantee the 6 digits after the decimal  
point; else a bit more work is required:

py> timestr = "00:00:25.886"
py> h, m, s = timestr.split(":")
py> if '.' in s:
...   s, us = s.split('.')
...   us = us[:6].ljust(6, '0')
... else:
...   us = 0
...
py> datetime.time(int(h), int(m), int(s), int(us))
datetime.time(0, 0, 25, 886000)

-- 
Gabriel Genellina




More information about the Python-list mailing list