如何在巨蟒熊猫中打印一年当前月份的剩余月份?



创建这个for循环是为了通过传递范围来打印之前的月份,但是我想要显示当前月份之后的月份,例如month = 6,那么它应该打印一年中剩余的月份

year = 2021
month = 6
for i in range(1,month):
thdate = datetime(year,i,calendar.monthrange(year, i)[1])
thdate

你可以试试

year = 2021
month = 6
for i in range(month, 13):  # <--- Modify the `range` to [month, 13)
thdate = datetime(year,i,calendar.monthrange(year, i)[1])

另一个不同的解决方案是使用monthdelta包。

类似于do-while循环,或者你可以用其他方式(使用常规的for循环):

from datetime import date
import monthdelta as md
curr_date = date(2021, 6, 1)
y = curr_date.year
first_iter = True
while first_iter or y == curr_date.year:
print(curr_date.month)
curr_date = curr_date + md.monthdelta(1)
first_iter = False

最新更新