python 给到达时间和出发时间 求两人都在休息室的时间
时间: 2024-04-30 08:19:16 浏览: 15
假设两人到达和出发的时间分别为 A_arrival, A_departure, B_arrival, B_departure,其中 A 表示第一个人,B 表示第二个人,那么两人都在休息室的时间可以按照下面的方法计算:
1. 计算两人的最早到达时间 earliest_arrival = max(A_arrival, B_arrival)
2. 计算两人的最晚出发时间 latest_departure = min(A_departure, B_departure)
3. 如果 earliest_arrival >= latest_departure,说明两人没有交集,返回 0
4. 否则,两人在休息室的时间为 latest_departure - earliest_arrival
下面是一个简单的 Python 实现:
```python
def rest_time(A_arrival, A_departure, B_arrival, B_departure):
earliest_arrival = max(A_arrival, B_arrival)
latest_departure = min(A_departure, B_departure)
if earliest_arrival >= latest_departure:
return 0
else:
return latest_departure - earliest_arrival
```
可以调用该函数来计算两人在休息室的时间,例如:
```python
A_arrival = "2022-01-01 08:00:00"
A_departure = "2022-01-01 10:00:00"
B_arrival = "2022-01-01 09:00:00"
B_departure = "2022-01-01 11:00:00"
print(rest_time(A_arrival, A_departure, B_arrival, B_departure)) # 输出 1 小时
```
该实现中,时间可以使用字符串表示,但需要保证字符串的格式正确。如果需要更高的时间处理精度,可以使用 Python 的 datetime 模块来处理时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)