简体   繁体   中英

“How to calculate difference in succesive time values in Python”

I'am trying to calculate the difference between string time values but i could not read microseconds format. Why i have this type of errors ? and how i can fix my code for it ?

I have already tried "datetime.strptime" method to get string to time format then use pandas.dataframe.diff method to calculate the difference between each item in the list and create a column in excel for it.

```
from datetime import datetime
import pandas as pd 

for itemz in time_list:
    df = pd.DataFrame(datetime.strptime(itemz, '%H %M %S %f'))
    ls_cnv.append(df.diff())

df = pd.DataFrame(time_list)
ls_cnv = [df.diff()]

print (ls_cnv)

```

I expect the output to be

ls_cnv = [NaN, 00:00:00, 00:00:00] 
time_list = ['10:54:05.912783', '10:54:05.912783', '10:54:05.912783']

but i have instead (time data '10:54:05.906224' does not match format '%H %M %S %f')

只是因为您的时间格式必须包含冒号和这样的点

"%H:%M:%S.%f"

The error you get is because you are using strptime wrong.

df = pd.DataFrame(datetime.strptime(itemz, '%H:%M:%S.%f'))

The above would be the correct form, the one passed from your time_list but that's not the case. You create the DataFrame in the wrong way too. DataFrame is a table if you wish of data. The following lines will create and replace in every loop a new DataFrame for every itemz which is one element of your list at time. So it will create a DataFrame with one element in the first loop which will be '10:54:05.912783' and it will diff() that with itself while there is no other value.

for itemz in time_list:
    df = pd.DataFrame(datetime.strptime(itemz, '%H %M %S %f'))
    ls_cnv.append(df.diff())

Maybe what you wanted to do is the following:

from datetime import datetime
import pandas as pd

ls_cnv = []
time_list = ['10:54:03.912743', '10:54:05.912783', '10:44:05.912783']

df = pd.to_datetime(time_list)
data = pd.DataFrame({'index': range(len(time_list))}, index=df)
a = pd.Series(data.index).diff()
ls_cnv.append(a)
print (ls_cnv)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM