Home > Software engineering >  Strptime() in python 3 is producing an unwanted output when converting string times to datetime obje
Strptime() in python 3 is producing an unwanted output when converting string times to datetime obje

Time:10-12

I have a string of times in the 'H|M|S' format, where H is hours, M is minutes, S is seconds. I am trying to convert these into datetimes in the format of H::M::S.

input: 01|15|59, 1|47|6, 01|17|20, 1|32|34, 2|3|17

desired output: [1::15::59, 1::47:06, 1::17::20, 1::32::34, 2::3::17]

My code is

def stat(strg):                                                                     
    strg = strg.split(',')
    strg = [item.replace('|', '::').strip() for item in strg]
    return [datetime.strptime(item, '%H::%M::%S').time() for item in strg]

The output is:

[datetime.time(1, 15, 59), datetime.time(1, 47, 16), datetime.time(1, 17, 20), datetime.time(1, 32, 34), datetime.time(2, 17, 17)]

I want my ouput to be a list of times in the format 'H::M::S' rather than the ouput shown above. How do I format this correctly?

CodePudding user response:

You can simply convert to list and then replace to get desired output if you no need to worry about type of date elements

dt ="01|15|59, 1|47|6, 01|17|20, 1|32|34, 2|3|17"
dt_list = dt.split(",")

dt_list = [w.replace('|', '::') for w in dt_list]
print(dt_list)

output#

['01::15::59', ' 1::47::6', ' 01::17::20', ' 1::32::34', ' 2::3::17']

CodePudding user response:

To get your desired output, you need to use strftime function which formats the datetime obj in a desired manner

return [datetime.strptime(item, '%H::%M::%S').time().strftime('%H::%M::%S') for item in srtg]
  • Related