-2

I have a list of date and time as a string,

a = ['2015-07-13 00:24:35.058', '2015-07-13 00:25:06.606', '2015-07-13 00:25:54.643']

I am trying to convert it, using this piece of code,

for d in a:
    dt = datetime.datetime.strptime(d, '%Y-%m-%d %H:%M:%S')
    print "Converted time: ", dt

but it prompts an error: ValueError('unconverted data remains: .058',) Please help me.
I have also tried using %c, %f instead of %S but it didn't help.

MHS
  • 2,260
  • 11
  • 31
  • 45
  • I found solution in **first** link when I googled this... Please do some [research](https://www.google.cz/webhp?ie=utf-8&oe=utf-8&gws_rd=cr&ei=cB7LVeLuH4W4adPHkdAF#safe=off&q=python+datetime+milliseconds) before you ask. – David Mašek Aug 12 '15 at 10:27
  • @DavidMašek I didn't want to waste anybody's time. I googled it and found several links of python libraries, when I was hopeless I turned to stackoverflow and questioned it. thanks for such appreciation. – MHS Aug 12 '15 at 10:30
  • Ok, sorry, maybe I overreacted - it's just that there's a LOT of questions that can be solved with simple google search. See for example [this](http://stackoverflow.com/questions/7588511/format-a-datetime-into-a-string-with-milliseconds) SO question... – David Mašek Aug 12 '15 at 10:35

1 Answers1

6

Use the format %f for the microsecond part do not remove the %S part, use both together, the complete format - '%Y-%m-%d %H:%M:%S.%f'

Example/Demo -

>>> a = ['2015-07-13 00:24:35.058', '2015-07-13 00:25:06.606', '2015-07-13 00:25:54.643']
>>> import datetime
>>> for d in a:
...     dt = datetime.datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f')
...     print "Converted time: ", dt 
...
Converted time:  2015-07-13 00:24:35.058000
Converted time:  2015-07-13 00:25:06.606000
Converted time:  2015-07-13 00:25:54.643000
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176