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!
Asked
Active
Viewed 34 times
1
-
Possible duplicate of [Parsing time string in Python](http://stackoverflow.com/questions/10494312/parsing-time-string-in-python) – Aran-Fey Jul 17 '16 at 18:52
3 Answers
1
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'

Psidom
- 209,562
- 33
- 339
- 356
-
how would you implemented to several values just like 203045 in a row? – user665997 Jul 17 '16 at 20:29
-
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. – Psidom Jul 17 '16 at 20:35
1
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'

Hamrouni Ahmed Amine
- 26
- 3
-
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?? – user665997 Jul 17 '16 at 21:58
0
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'

Hamrouni Ahmed Amine
- 26
- 3