I'm trying to import and visualize data from an Excel sheet using Pandas and Matplotlib.
The data file is in ISO 8601 with 4 Hz. What I want to do is show the x-axis with only HH:MM:SS and a lower tick rate, 30-60 seconds.
I managed to convert from ISO 8601 to HH:MM:SS with the following:
data["Time UTC"] = [element[10:19] for element in data["Time_4Hz"]]
Then I want to define the left and right range as follows:
for element in data.index:
x_limit_l = min(datetime.strptime(element, '%H:%M:%S'))
x_limit_r = max(datetime.strptime(element, '%H:%M:%S'))
and get the following error:
ValueError: time data ' 08:45:27' does not match format '%H:%M:%S'
The time should be a string with the correct format, what could be the reason for the error?
I tried looping through the "Time UTC" colum with:
for element in data.index:
x_limit_l = min(datetime.strptime(element, '%H:%M:%S'))
x_limit_r = max(datetime.strptime(element, '%H:%M:%S'))
I also tried getting the time directly from the column with:
x_limit_l = min(datetime.strptime("data.index", '%H:%M:%S'))
x_limit_r = max(datetime.strptime("data.index", '%H:%M:%S'))
CodePudding user response:
Looks like there are spaces in the str
which raises the Exception
. To fix that, you can use strip
function. If you don't know about it, it just removes spaces from start and end of str
.
x_limit_l = datetime.strptime(element.strip(), '%H:%M:%S')
EDIT: For the error you are getting after implementing, there's no use of using min
in a single value excluding the fact that datetime
object cannot be iterable.
Here's a working work-around, assuming you can apply logic yourself:
x_limit_list = list() #Creates a list
for element in data.index:
#Just showing of one element
x_limit_l = x_limit_list.append(datetime.strptime(element, '%H:%M:%S'))
#Adds the current x_limit_l value to the list
#After the loop ends, it finds the min value
x_limit_l = min(x_limit_list)
#If you want it in Hour, Min and Sec format:
x_limit_l = min(x_limit_list).strftime('%H:%M:%S')
CodePudding user response:
Should it not be data["Time UTC"] = [element[11:19] for element in data["Time_4Hz"]]?
import pandas as pd
from datetime import datetime
lst = ['2022-12-06 12:42:40Z','2022-12-06 12:44:40Z','2022-12-06 12:46:40Z','2022-12-06 12:48:40Z']
data = pd.DataFrame(lst, columns =['Time_4Hz'])
data["Time UTC"] = [element[11:19] for element in data["Time_4Hz"]]
x_limit_l = print(max(data["Time UTC"]))
x_limit_r = print(min(data["Time UTC"]))
print(x_limit_l, x_limit_r)
No need to loop