以下是df的示例:
pId tPS tLL dZ
129 2019-12-02 15:04:09 2019-12-02 15:06:31 5f723
129 2019-12-02 15:04:15 2019-12-02 15:06:37 5f723
129 2019-12-02 15:05:15 2019-12-02 15:07:37 5f723
129 2019-12-02 15:05:18 2019-12-02 15:07:40 5f723
129 2019-12-02 15:05:24 2019-12-02 15:07:46 5f723
pID是一个人的ID,我试图检查每个ID的进入、退出和持续时间
代码如下:
from datetime import datetime
stats=df.sort_values(by=['pId', 'tPS', 'tLL'])[['pId', 'tPS', 'tLL', 'dZ']]
pid = ''
enter_t = ''
exit_t = ''
enter_exit_times=[]
for ind, row in stats.iterrows():
if pid =='':
enter_t = row['tPS']
print(enter_t)
if row['pId']!= pid or ((datetime.strftime(row['tLL'], "%Y-%m-%d %H:%M:%S")
- datetime.strftime(exit_t, "%Y-%m-%d %H:%M:%S")).total_seconds()>2*60*60):
duration = (datetime.strptime(exit_t, "%Y-%m-%d %H:%M:%S") -
datetime.strptime(enter_t, "%Y-%m-%d %H:%M:%S"))
enter_exit_times.append([pid, enter_t, exit_t, duration.total_seconds()])
pid = row['pId']
enter_t = row['tPS']
enter_exit_times.append([pid, enter_t, exit_t])
enter_exit_times_df = pd.DataFrame(enter_exit_times)
所以这里
pid
是identer_t
是输入的时间exit_t
是退出时间tPS
是最及时的tLL
是超时时间李>然后我创建了一个列表,我在下面为它写了一个循环。最初,我通过一个for
循环来运行它,在这个循环中我遍历数据帧的行。因此有两个if
循环,一个带有pid
的循环,其中空值表示它需要取row[tPS]
,如果不是,则必须通过not循环运行。然后我计算持续时间,然后将这些值附加到进入-退出时间
我得到这个错误:
2019-12-02 15:04:09
---------------------------------------------------------------------------
ValueError Traceback (most recent callast)
<ipython-input-411-fd8f6f998cc8> in <module>
12 if row['pId']!= pid or ((datetime.strftime(row['tLL'], "%Y-%m-%d %H:%M:%S")
13 - datetime.strftime(exit_t, "%Y-%m-%d %H:%M:%S")).total_seconds()>2*60*60):
---> 14 duration = (datetime.strptime(exit_t, "%Y-%m-%d %H:%M:%S") -
15 datetime.strptime(enter_t, "%Y-%m-%d %H:%M:%S"))
16 enter_exit_times.append([pid, enter_t, exit_t, duration.total_seconds()])
~/opt/anaconda3/lib/python3.7/_strptime.py in _strptime_datetime(cls, data_string, format)
575 """Return a class cls instance based on the input string and the
576 format string."""
--> 577 tt, fraction, gmtoff_fraction = _strptime(data_string, format)
578 tzname, gmtoff = tt[-2:]
579 args = tt[:6] + (fraction,)
~/opt/anaconda3/lib/python3.7/_strptime.py in _strptime(data_string, format)
357 if not found:
358 raise ValueError("time data %r does not match format %r" %
--> 359 (data_string, format))
360 if len(data_string) != found.end():
361 raise ValueError("unconverted data remains: %s" %
**ValueError: time data '' does not match format '%Y-%m-%d %H:%M:%S'**
错误的原因是
exit_t
没有设置在循环中的任何位置。这是一个空字符串。您在循环之前将其设置为exit_t = ''
,但之后再也不会设置。这就是strptime
在这里抛出错误的原因:解决方法是简单地将其正确设置为
"tLL"
(如果我理解正确的话)但是我想进一步说,我认为您正在使代码变得比它应该如何复杂得多。我的理解是,您只需要计算
"tPS"
(in time)和"tLL"
(out time)之间的持续时间。因为您已经在每一行上进行了迭代,所以只需要适当地分配值然后使用
strptime
将日期时间字符串转换为日期时间对象然后计算持续时间
最后,将其添加到列表中
没有必要跟踪
"pId"
以下是完整的代码:
和输出数据帧:
如果只想获取一天中特定时间段的进入/退出时间,可以为开始时间和结束时间创建
datetime
对象,并定期进行比较:因此,您可以为要附加到
enter_exit_times
的内容添加一个过滤器:相关问题 更多 >
编程相关推荐