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.
Asked
Active
Viewed 82 times
0
-
Have you checked out: https://stackoverflow.com/questions/466345/converting-string-into-datetime/466376#466376 – Pete Apr 09 '20 at 12:20
-
1Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime). You should also read python documentation on [`time`](https://docs.python.org/3.7/library/time.html#time.strptime) built-in module – DarK_FirefoX Apr 09 '20 at 12:23
-
it adds date even when there is no date in it. – Rahul Apr 09 '20 at 12:50
2 Answers
0
So you can use
import datetime
result = datetime.datetime.strptime(strtempTime, '%H:%M:%S.%f').time()
print(result, type(result))
-
-
I tried the code below but it's converting it to date and time. temptime=datetime.strptime(temptime,'%H:%M:%S.%f.%f'[:-3]) print("temptime:",temptime) – Rahul Apr 09 '20 at 12:43
-
0
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

Gauthik
- 29
- 3
-
I tried the code below but it's converting it to date and time. temptime=datetime.strptime(temptime,'%H:%M:%S.%f.%f'[:-3]) print("temptime:",temptime) – Rahul Apr 09 '20 at 12:48
-
yes, datetime format contains the date as well, but there is no problem. If you need to use the date somewhere in your code, you can use the function "strtime" which will convert your datetime objet to string. Your datetime object will be someting like that : datetime_obj = datetime.strptime("09:01:02.518", "%H:%M:%S.%f"), and in order to get the time as string you may use : print(datetime.strftime(datetime_obj, "%H:%M:%S.%f")) – Gauthik Apr 09 '20 at 13:02