python 怎么获取本年已过的月份并进行输出
时间: 2024-03-25 19:36:32 浏览: 18
你可以使用Python的datetime模块来获取当前年份和月份,然后使用for循环来输出本年已过的月份,代码如下:
```
import datetime
# 获取当前年份和月份
now = datetime.datetime.now()
year = now.year
month = now.month
# 输出本年已过的月份
for i in range(1, month):
print('{}年{}月'.format(year, i))
```
运行结果:
```
2022年1月
2022年2月
2022年3月
2022年4月
2022年5月
2022年6月
2022年7月
2022年8月
2022年9月
2022年10月
2022年11月
```
相关问题
Python输入某年某月某日,判断这一天是这一年的第几天并输出结果
以下是两种Python判断某年某月某日是这一年的第几天的例子:
1.将每月的天数进行相加,就可得到结果
```python
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
day = int(input('请输入日期:'))
mouths = [0,31,28,31,30,31,30,31,31,30,31,30,31]
if year % 400 == 0 or year % 4 == 0:
mouths[2] = 29
if 0 < month <= 12:
days = 0
for item in range(month):
sum = mouths[item]
days = days + sum
day_s = days + day
print(f'今天是今年的第{day_s}天')
else:
print('输入日期超出范围')
```
2.以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天
```python
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
day = int(input('请输入日期:'))
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 <= month <= 12:
sum = months[month -1]
sum += day
else:
print ('您输入的日期超出范围!!')
leap = 0
if (year % 400 == 0) or ((year %4==0) and (year % 100 !=0)):
leap=1
if (leap == 1) and (month > 2):
sum += 1
print ('今天是今年的第%s天.' % sum)
```
按月输出本年日历,星期日在前。将上述日历输出至文件。
您可以使用以下Python代码按月输出本年日历,并将它们输出到文件中:
```python
import sys
import calendar
# 获取当前年份
year = int(input("请输入年份:"))
# 按月输出日历
for month in range(1, 13):
# 获取当前月份的日历文本
cal_text = calendar.monthcalendar(year, month)
# 将星期日移到第一列
for week in cal_text:
if week[0] == 0:
week.pop(0)
week.append(0)
# 将日历文本写入文件
with open('calendar.txt', 'a') as f:
sys.stdout = f
print(calendar.month_name[month], year)
print('Su Mo Tu We Th Fr Sa')
for week in cal_text:
print(' '.join(['{:2}'.format(day) if day > 0 else ' ' for day in week]))
print()
```
以上代码中,我们使用了`calendar`模块的`monthcalendar()`函数来获取日历文本。然后,我们将星期日移到第一列以满足要求,并将日历文本写入`calendar.txt`文件中。注意,在写入文件之前,我们使用`sys.stdout`将输出重定向到文件,这样就可以将日历文本直接写入文件中了。