Search code examples
pythonstringdatetimematplotlibstrptime

Converting list of strings with decimals into datetime


I have the following list of strings that looks like this

dates_list = ['7.0:2.0', '6.0:32.0', '6.0:16.0', '6.0:16.0', '6.0:17.0', '6.0:2.0', '6.0:1.0']

I want to plot this into a graph but I need to convert into date time of minutes and seconds (%M:%S)

I tried using strptime

for i in dates_list:
        datetime_object = datetime.strptime(i,'%M:%S')

I get the following error:

ValueError: time data '7.0:2.0' does not match format '%M:%S'

Is there a way to handle floats or do I have to convert the strings to int and remove the decimals?


Solution

  • This will allow you to introduce any decimal:

    from datetime import datetime
    
    for i in dates_list:
      time_list = i.split(':')
      minute_decimal = time_list[0].split('.')[1]
      second_decimal = time_list[1].split('.')[1]
      datetime_object = datetime.strptime(i,'%M.{0}:%S.{1}'.format(minute_decimal,second_decimal)).time()