You can parse a string representing a time, in Python, by using the strptime
method. There are numerous working examples on stackoverflow:
Converting string into datetime
However, what if your string represented a time range, as opposed to a specific time; how could you parse the string using the strptime
method?
For example, let’s say you have a user input a start and finish time.
studyTime = input("Please enter your study period (start time – finish time)")
You could prompt, or even force, the user to enter the time in a specific format.
studyTime = input("Please enter your study period (hh:mm - hh:mm): ")
Let’s say the user enters 03:00 PM – 05:00 PM
. How can we then parse this string using strptime
?
formatTime = datetime.datetime.strptime(studyTime, "%I:%M %p")
The above formatTime
would only work on a single time, i.e. 03:00 PM, not a start – finish time, 03:00 – 05:00. And the following would mean excess format data and a ValueError
would be raised.
formatTime = datetime.datetime.strptime(studyTime, “%I:%M %p - %I:%M %p”)
Of course there are alternatives, such as having the start and finish times as separate strings. However, my question is specifically, is there a means to parse one single string, that contains more than one time representation, using something akin to the below.
formatTime = datetime.datetime.strptime(studyTime, “%I:%M %p - %I:%M %p”)