0

I am trying to convert the following list of strings :

['0:00:01.138000', '0:00:03.733000', '0:00:01.250000', '0:00:01.127000']

But when I try the following code :

T = '%H:%M:%S.%f'

for i in range(len(Normal_key)):
    try:
        Normal_key[i]=datetime.strptime(Normal_key[i], T)
    except ValueError:
        continue

print(Normal_key)

The list now contains data information for some reason even though no date was specified:

[datetime.datetime(1900, 1, 1, 0, 0, 1, 138000), datetime.datetime(1900, 1, 1, 0, 0, 3, 733000), datetime.datetime(1900, 1, 1, 0, 0, 1, 250000)]
AB2000
  • 31
  • 4
  • That's just a default date added; you could use `datetime.strptime(Normal_key[i], T).time()` to strip the date – FObersteiner May 17 '21 at 11:52
  • It still returns the same exact format. – AB2000 May 17 '21 at 11:54
  • You should now have time objects instead of datetime objects. What "*format*" do you expect exactly? – FObersteiner May 17 '21 at 11:58
  • I wanted to get the milliseconds and for that the following worked: (datetime.strptime(Normal_key[i], T).time().microsecond/1000)) – AB2000 May 17 '21 at 12:49
  • ok so what you're actually dealing with are duration (`timedelta` in Python). Note that the `datetime.strptime` method will fail if for example the hour exceeds 23. You might want to have a look at [this question](https://stackoverflow.com/q/4628122/10197418) as well. – FObersteiner May 17 '21 at 12:59

1 Answers1

0

I think this is because you are using datetime module so it is by default adding the starting date to it. you can extract just the time using

datetime.strptime("0:00:01.138000", "%H:%M:%S.%f").time()
Yash
  • 223
  • 2
  • 11
  • It works if i do this: (datetime.strptime(Normal_key[i], T).time().microsecond/1000) and convert it from microseconds to milliseconds . – AB2000 May 17 '21 at 12:48