Python循环打印一个月的时期
时间: 2023-11-16 14:09:50 浏览: 28
你可以使用Python的datetime和calendar模块来实现循环打印一个月的日期。下面是一个示例代码:
```python
import datetime
import calendar
# 获取当前日期
now = datetime.datetime.now()
# 获取当前月份的日历
cal = calendar.monthcalendar(now.year, now.month)
# 循环打印日期
for week in cal:
for day in week:
if day == 0:
print(" ", end="")
else:
print("{:2d}".format(day), end=" ")
print("")
```
输出结果类似于:
```
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
```
在上面的代码中,我们首先使用datetime模块获取当前日期,然后使用calendar.monthcalendar()函数获取当前月份的日历。这个函数返回一个二维列表,其中每个元素代表一个日期。如果某个元素的值为0,表示这个日期不在当前月份内。最后,我们使用两层循环遍历这个二维列表,打印出日期。注意,在打印日期的时候,我们使用了格式化字符串"{:2d}"来保证每个日期占用两个字符的宽度,这样输出的格式会更整齐。