【发布时间】:2019-12-19 20:21:27
【问题描述】:
我有一个包含两列时间戳的数据框,我想减去它们,以便得到小时和分钟的时差。
ColA Timestamp Timestamp2
1 06:40:00 17:40:00
2 06:29:00 16:29:00
3 07:05:00 15:29:00
4 06:43:00 18:55:00
我尝试了以下代码,但它只给了我小时数(一个整数)。
for m in range(4):
j = df.iloc[m,0]
d1 = df.iloc[m,2]
d2 = df.iloc[m,1]
td = d1-d2
q = td.total_seconds() / 3600
print ("Timeinterval %s is %d hours." %(j, q))
我也用函数尝试过(它给了我一个元组,或者如果我忽略逗号后面的东西,我会得到与以前相同的结果):
def days_hours_minutes(td):
return td.seconds//3600, (td.seconds//60)%60
还有,
def datetime_to_float(d):
return d.timestamp()
抛出“'Timedelta' 对象没有属性 'timestamp'”。
两个时间戳之间的差异有效,但我希望输出为浮点数(例如:8.5 小时)。
【问题讨论】:
-
你能跑
df["Timestamp"].dtype吗? -
td.total_seconds() / 3600的结果是一个浮点数,但后面的print输出的值是%d,是整数。
标签: python python-3.x dataframe datetime timedelta