Stephen Yorke
Stephen Yorke

Reputation: 307

Converting strings to time

I have strings that I need to convert to times. Examples are:

I can easily convert the first string using:

print(cleant,(datetime.strptime(cleant,"%M%S")).strftime("%M:%S"))

If I try to do the same for str2 and 3 then the first 2 digits are taken as the minutes or hours respectively and a 0 is added to the beginning of the seconds and the results are shown as:

How can I have it so the 0 would be added to the first section of the time? If there is no hour but less than 10 minutes then the 0 is added there if the hour exists but is less than 10 the 0 is added there. Maybe there is a format that I'm missing that datetime already has.

Upvotes: 0

Views: 36

Answers (1)

Maksym Polshcha
Maksym Polshcha

Reputation: 18358

I think you missed : in strptime. Try to use

try:
    # this handles 23:11 and 2:23
    datetime.strptime(cleant,"%M:%S")
except ValueError:
    # this handles 1:12:13
    datetime.strptime(cleant,"%H:%M:%S")

Upvotes: 2

Related Questions