python的datetime求本周起止日期,上周起止日期,本月起止日期,上月起止日期
时间: 2023-07-16 12:15:37 浏览: 110
以下是Python的datetime实现本周、上周、本月和上月起止日期的代码:
```python
import datetime
# 本周起止日期
now = datetime.datetime.now()
start_of_week = now - datetime.timedelta(days=now.weekday())
end_of_week = start_of_week + datetime.timedelta(days=6)
# 上周起止日期
start_of_last_week = start_of_week - datetime.timedelta(days=7)
end_of_last_week = end_of_week - datetime.timedelta(days=7)
# 本月起止日期
start_of_month = datetime.datetime(now.year, now.month, 1)
if now.month == 12:
end_of_month = datetime.datetime(now.year+1, 1, 1) - datetime.timedelta(days=1)
else:
end_of_month = datetime.datetime(now.year, now.month+1, 1) - datetime.timedelta(days=1)
# 上月起止日期
last_month = now.month - 1 if now.month > 1 else 12
last_year = now.year - 1 if last_month == 12 else now.year
start_of_last_month = datetime.datetime(last_year, last_month, 1)
end_of_last_month = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(days=1)
# 输出起止日期
print("本周起止日期:", start_of_week.date(), "-", end_of_week.date())
print("上周起止日期:", start_of_last_week.date(), "-", end_of_last_week.date())
print("本月起止日期:", start_of_month.date(), "-", end_of_month.date())
print("上月起止日期:", start_of_last_month.date(), "-", end_of_last_month.date())
```
其中关键的方法是`datetime.timedelta()`表示时间差,例如`datetime.timedelta(days=7)`表示7天时间差。`datetime.datetime()`则表示一个具体的日期时间。
阅读全文