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?
CodePudding user response:
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()
CodePudding user response:
Try this, you need to correctly specify the format
import datetime as dt
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']
for i in dates_list:
datetime_object = dt.datetime.strptime(i,'%M.0:%S.0').time()
print(datetime_object)
CodePudding user response:
I would do this with pd.to_datetime(). However, it would add unnecessary date information which you can then remove with strftime:
[x.strftime("%M:%S") for x in pd.to_datetime(dates_list,format='%M.0:%S.0')]
Returning:
['07:02', '06:32', '06:16', '06:16', '06:17', '06:02', '06:01']