0

I have certain time values in excel as :

Data:

932    
1253    
5

Coversions:

When trying to process them as a time string I get:

TIME_FMT= "%H%M"

datetime.strptime('932',TIME_FMT).time()
# Output : datetime.time(9, 32)

datetime.strptime('1253',TIME_FMT).time()
# Output : datetime.time(12, 53)

datetime.strptime('5',TIME_FMT).time()
# Output : ValueError: time data '5' does not match format '%H%M'

How can I catch such exceptional values for normal processing?

I understand that 5 does not match the format "%H%M".

0

1 Answer 1

1

If you add some leading '0's to the string, the conversion can proceed like:

Code:

def from_time_string(time_string):
    TIME_FMT = "%H%M"
    leading = '0' * (3 - len(time_string))
    return dt.datetime.strptime(leading + time_string, TIME_FMT).time()

Test Code:

for i in ('932', '1253', '5'):
    print(from_time_string(i))

Results:

09:32:00
12:53:00
00:05:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.