1

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!

1

3 Answers 3

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' 
Sign up to request clarification or add additional context in comments.

2 Comments

how would you implemented to several values just like 203045 in a row?
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.
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' 

1 Comment

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??
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' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.