+ 1

Converting time string(H:MM) to (HH:MM)

Working on a problem and want to know how to convert string "1:15 PM" to "01:15 PM" in python?

13th Sep 2021, 9:24 AM
Robert Haugland
Robert Haugland - avatar
6 Answers
13th Sep 2021, 11:51 AM
SAN
SAN - avatar
+ 6
Robert Haugland , it would be great if you could share your code with us. just showing the samples may mislead us to a wrong or not suitable answer. thanks and happy coding!
13th Sep 2021, 9:31 AM
Lothar
Lothar - avatar
+ 4
Well you need to make it count haw many characters are in the string ... So ✨: 📌If the length is 8 : The string do not require to convert it 📌If the length is 7 : You need to add "0" at the beginning If there's anything else tell me ...because i didn't understand exactly what you want ☄️
13th Sep 2021, 9:35 AM
Moha Riad
Moha Riad - avatar
+ 2
Robert Haugland There are a couple of ways. One way is as follows If you turn the integer into a string, you could ascertain the length of the string. If len(string) == 1 put '0' in front of your num using concatenation
13th Sep 2021, 9:34 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
San, I used the code you gave and tweeked oh so slightly to fit my situation and it worked: def Format(tm): time=tm[:-2].split(":") min=int(time[0]) sec=int(time[1]) if min<10: min='0'+str(min) else: min=str(min) if sec<10: sec='0'+str(sec) else: sec=str(sec) return min+':'+sec+' '+tm[-2:] I added + " " + in the return format to add the space between the mintures and "PM". Thanks. I iunderstand the code but I was just looking for a formatting short cut in one of the datetime or time import.modyles that utilizes the format code "%I:%M %p".
13th Sep 2021, 5:05 PM
Robert Haugland
Robert Haugland - avatar
+ 1
Okat, I am wanting to solve the Military time problem in the Coach Code Challenge. I pretty much have ut figured out how to actually convert the 12 hour clock to the 24 by the use of list slicing. I know that through the use of one of the time module imports that you can configure the format to what is needed. I recall doing this with a date format in one of the modules where I needed to add a "0" to the month or the date where the input did not have the padded "0". I have imported datetime, from datetime import datetime, and time. All of the references I have looked up on the internet show how to do this, but it also includes a date, which I do not need. So, my question is, is there a datetime or time import module that uses the format code "%I:%M %p" (HH:MM PM, according to the code key I found) to convert a string time input in the format of "1:15 PM" to that specified format? If so, what is the import module and what is the coding verbiage needed to get this done? If not, I will figure out it another way.
13th Sep 2021, 3:52 PM
Robert Haugland
Robert Haugland - avatar