Time Converting | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Time Converting

Hey Guys,I Made This Function To Convert Time From 12hours to 24hours And Vice Versa: def TimeConverter(time,mode): if mode not in ("12to24","24to12"): raise ValueError(f"Unknown Mode: '{mode}'") from datetime import datetime if mode == "12to24": time_converted = datetime.strptime(time, "%I:%M:%S %p") string_time = datetime.strftime(time_converted, "%H:%M:%S") return string_time else: time_converted = datetime.strptime(time, "%H:%M:%S") string_time = datetime.strftime(time_converted,"%I:%M:%S %p") return string_time It Works Properly But The Problem Is That When The User Enters Time Like ("12:35 AM") Or ("18:42:33:21.6") An Error Occurs As I Wrote In My Code That The Format Of The Time Should Be:(Hours:Minutes:Seconds) How Can I Make The Code Suitable For All Formats?

5th Jun 2020, 3:50 PM
Ahmad Tarek
Ahmad Tarek - avatar
3 Answers
+ 5
I hae put a few thoughts and code snippets in a file. Hope this helps! https://code.sololearn.com/cgM75ZlOq08h/?ref=app
5th Jun 2020, 6:52 PM
Lothar
Lothar - avatar
+ 1
I Solved It With The Third Party Library dateutil
5th Jun 2020, 10:45 PM
Ahmad Tarek
Ahmad Tarek - avatar