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!
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'
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'
try this to remove the two last digits if they are equal to zero :
import re
ch = "20304500"
print ":".join([e for e in re.findall('\d{2}',ch) if e!="00"])
# '20:30:45'
or whatever (the two last digits) :
import re
ch = "20304500"
print ":".join(re.findall('\d{2}',ch)[:-1])
# '20:30:45'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.