how to convert string to time in python

88 views Asked by At

I have (9:00:00.000) as a string. I want to convert it to actual time. In format of hh:mm:ss.miliseconds. I think I have to use 'datetime' package but I don't know how. I have strtempTime = '9:00:00.000' in code.

2

There are 2 answers

3
mooniean On

So you can use

import datetime

result = datetime.datetime.strptime(strtempTime, '%H:%M:%S.%f').time()
print(result, type(result))
2
Gauthik On

you should use the function "strptime" from the datetime module. it should be something like that :

from datetime import datetime

print(datetime.strptime("09:00:00.000", "%H:%M:%S.%f"))

Check documentation for more informations : https://docs.python.org/2/library/datetime.html