datetime.time() class - How to pass it a time string?
python at jayloden.com
Thu Jul 26 09:32:01 CEST 2007
Ben Finney wrote:
> Neil Cerutti <horpner at yahoo.com> writes:
>> On 2007-07-24, Robert Dailey <rcdailey at gmail.com> wrote:
>>> I have a string in the following format:
>>> 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.
>> Consult the documentation about time.strptime (to start) and then
>> datetime.strptime (which refers back to the time.strptime docs,
>> in a rather unfortunate manner).
> Unfortunately 'strptime' also only seems to parse the components as
> >>> import datetime
> >>> time_format = "%H:%M:%S"
> >>> time_value = datetime.datetime.strptime("09:45:31.064371", time_format)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "/usr/lib/python2.5/_strptime.py", line 334, in strptime
> ValueError: unconverted data remains: .064371
> The same thing happens with 'time.strptime'. So this isn't yet a
> solution for the OP.
How about something like this?
>>> import time
>>> import datetime
>>> time_fmt = "%H:%M:%S"
>>> timestamp = "00:00:25.886411"
>>> stamp,msec = timestamp.split('.')
>>> dtime = datetime.datetime(*(time.strptime(stamp, time_fmt)[0:6] + (int(msec),)))
datetime.datetime(1900, 1, 1, 0, 0, 25, 886411)
More information about the Python-list