I've been trying to get this time formatted value from 203045 to 20:40:45 in python. I clearly have no clue where to start. Any help will be appreciated! Thanks!
3 Answers
Use strptime and strftime functions from datetime, the former constructs a datetime object from string and the latter format datetime object to string with specific format:
from datetime import datetime datetime.strptime("203045", "%H%M%S").strftime("%H:%M:%S") # '20:30:45' 2 Comments
user665997
how would you implemented to several values just like 203045 in a row?
akuiper
Use
list-comprehension is not a bad choice. Something like [datetime.strptime(str1, "%H%M%S").strftime("%H:%M:%S") for str1 in values]. Replace the values here with your actual values.you can also play with the regular expression to get the same result :)
import re ch = "203045" print ":".join(re.findall('\d{2}',ch)) # '20:30:45' 1 Comment
user665997
that worked but my question now lies as follow. If the number I have is 20304500 and I want this 20:30:45 without the last 2 digits "00" how can i do that??