时间差之天数计算123
时间: 2023-09-15 10:15:14 浏览: 51
对于给定的两个日期(假设为start_date和end_date),可以通过以下方式计算它们之间的天数差:
1. 将日期转换为Python中的datetime对象:
```python
import datetime
start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
```
2. 计算两个日期之间的差值:
```python
delta = end - start
```
3. 获取差值的天数:
```python
days = delta.days
```
完整的代码如下:
```python
import datetime
start_date = "2021-01-01"
end_date = "2021-01-05"
start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
delta = end - start
days = delta.days
print("Days between {} and {}: {}".format(start_date, end_date, days))
```
输出结果为:
```
Days between 2021-01-01 and 2021-01-05: 4
```
阅读全文