繁体   English   中英

以小时为单位获取日期时间之间的差异,将两个舍入设置为 2

[英]Get the Difference between Datetime in terms of hours with two round off set to 2

通过四舍五入到 2 个小数点,以小时为单位获取两个日期时间之间的差异

> `Started                     Ended`                     Hours
   2020-10-01 09:29:20         2020-10-01 17:43:28         8.2
   2020-10-31 09:26:43         2020-10-31 18:57:40         9.5
   2020-10-31 09:18:57         2020-10-31 21:06:30         11.8

使用to_datetimeSeries.subSeries.dt.total_seconds ,最后除以Series.div并使用Series.round

df['Started'] = pd.to_datetime(df['Started'])
df['Ended'] = pd.to_datetime(df['Ended'])

df['new'] = df['Ended'].sub(df['Started']).dt.total_seconds().div(3600).round(2)
print (df)
              Started               Ended  Hours    new
0 2020-10-01 09:29:20 2020-10-01 17:43:28    8.2   8.24
1 2020-10-31 09:26:43 2020-10-31 18:57:40    9.5   9.52
2 2020-10-31 09:18:57 2020-10-31 21:06:30   11.8  11.79

另一个例子:

from datetime import datetime
beg = '08:00:10'
end = '17:16:24' 

print('end = ',end, 'type: ',type(end))

dur = datetime.strptime(end, '%H:%M:%S') - datetime.strptime(beg, '%H:%M:%S')

result = dur.total_seconds()/3600

result = round(result, 2)

print(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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