【发布时间】:2020-03-15 23:58:22
【问题描述】:
我以分钟为单位计算两次之间的差异。我有一个有四列的数据框:
df1:
Notified Start Time', 'Notified End Time', 'Actual Int Start Time', 'Actual Int End Time'
0 3/01/2020 9:00 3/01/2020 19:00 3/01/2020 9:00 3/01/2020 14:00
1 4/01/2020 9:00 4/01/2020 17:00 5/01/2020 9:00 5/01/2020 20:00
2 6/01/2020 8:30 6/01/2020 20:00 7/01/2020 8:30 7/01/2020 19:00
3 8/01/2020 8:30 8/01/2020 12:00 9/01/2020 9:00 9/01/2020 18:00
数据框的数据类型为:
Notified Start Time object
Notified End Time object
Actual Int Start Time object
Actual Int End Time object
我定义了一个函数,以分钟为单位计算两个日期之间的时间长度。
def calc_timeDiff(start_date,end_date):
fmt = '%d/%m/%Y %H:%M'
end_date = pd.to_datetime(end_date,format=fmt)
start_date = pd.to_datetime(start_date,format=fmt)
timediff = end_date - start_date
timediff =pd.to_datetime(timediff)
return (timediff.dt.hour * 60 + timediff.dt.minute + (timediff.dt.second/60)).astype(float)
当我在数据框中创建一个新列时,上述函数可以正常工作。例如,
df['ActualLength'] = calc_timeDiff(df['Actual Int Start Time'],df['Actual Int End Time'])
df['NotifiedLength'] = calc_timeDiff(df['Notified Start Time'],df['Notified End Time'])
当我尝试在计算某个值的其他函数中使用相同的函数时,问题就出现了。
def calc_value(func_df):
if func_df['NotifiedLength'] < func_df['ActualLength']:
if (func_df['Actual Int Start Time'] >= func_df['Notified Start Time']):
fullValue = func_df['ActualLength'] - calc_timeDiff(func_df['Notified End Time'],func_df['Actual Int End Time'])
return fullValue
我调用第二个函数在数据框中创建另一列:
df['ActualOutage'] = df.apply(calc_value,axis=1)
当我运行上面的代码时,它会抛出一个错误消息:
TypeError: ("<class 'pandas._libs.tslibs.timedeltas.Timedelta'> is not convertible to datetime", 'occurred at index 2')
它指向第一个函数的第 5 行(即timediff =pd.to_datetime(timediff))。我试图解决问题,但失败了。谁能指导我我在哪里犯了错误?
【问题讨论】:
-
注释掉那一行。
-
对不起,我没明白,你说的那条线是什么意思。
-
您不需要转换为日期时间对象。
timediff是/是 timedelta 对象。注释导致错误的行(将#放在它前面)。然后看看会发生什么。 - pandas.pydata.org/docs/user_guide/timedeltas.html#attributes -
我已经试过,当我注释掉转换行时,它会抛出 AttributeError 错误:'TimedeltaProperties' object has no attribute 'hour'(指向第一个函数的最后一行)跨度>
-
阅读我发布的文档链接 - total_minutes 应该是
timediff.dt.total_seconds() / 60。 - pandas.pydata.org/docs/user_guide/timedeltas.html#attributes
标签: python python-3.x python-datetime