Python获取最近的3个月格式为年/月例如2023/05;获取最近的五周,格式为年/周,例如2023/W18;获取最近的七天,格式为年月日,例如2023/05/26
时间: 2023-12-01 07:04:12 浏览: 209
python 输出指定格式的日期 (示例)
获取最近三个月的日期,格式为年/月,可以使用Python的datetime和timedelta模块,具体代码如下:
```python
import datetime
today = datetime.date.today()
three_months_ago = today - datetime.timedelta(days=3*30)
print("最近三个月的日期:")
while today > three_months_ago:
print(today.strftime("%Y/%m"))
today -= datetime.timedelta(days=1)
```
获取最近五周的日期,格式为年/周,可以使用Python的datetime和timedelta模块,具体代码如下:
```python
import datetime
today = datetime.date.today()
five_weeks_ago = today - datetime.timedelta(weeks=5)
print("最近五周的日期:")
while today > five_weeks_ago:
year, week_num, day_of_week = today.isocalendar()
print("{}/W{}".format(year, week_num))
today -= datetime.timedelta(days=7)
```
获取最近七天的日期,格式为年月日,可以使用Python的datetime和timedelta模块,具体代码如下:
```python
import datetime
today = datetime.date.today()
seven_days_ago = today - datetime.timedelta(days=7)
print("最近七天的日期:")
while today > seven_days_ago:
print(today.strftime("%Y/%m/%d"))
today -= datetime.timedelta(days=1)
```
阅读全文