Home > OS >  Is there a way to convert a non zero padded time string into a datetime?
Is there a way to convert a non zero padded time string into a datetime?

Time:12-27

I am looking a the strptime docs. It only specifies that it can read formatted times with zero padded strings like '01:00pm'. Is there a way I can read a time like '1:00am' using the strptime function?

CodePudding user response:

You can use the same format string to read a time like "1:00 AM" that isn't padded with zeroes. This is mentioned in note (9) of the technical details section:

When used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, %S, %j, %U, %W, and %V. Format %y does require a leading zero.

CodePudding user response:

You can probably pad the time using regular string functions assuming you only want to pad the hours.

time_string = '1:00am'

# Splits the string where ':' is
time_string_split = time_string.split(':')

# Uses a ternary operator to check the hour digits then pads accordingly
time_string_split[0] = '0'   time_string_split[0] if len(time_string_split[0]) < 2 else time_string_split[0]

# Joins it together again with a ':'
time_string = ':'.join(time_string_split)

print(time_string) # '01:00am'

Or a simpler approach

time_string = '1:00am'

time_string_split = time_string.split(':')

if len(time_string_split[0]) < 2: 
    time_string_split[0] = '0'   time_string_split[0]

time_string = ':'.join(time_string_split)

print(time_string) # '01:00am'

Hope this helps!

  • Related