如何在 Python 中的当前月份和年份值停止循环

How to stop for loop at present month and year value in Python

目前我的代码如下:

   mon = datetime.date.today().strftime("%m")
   month = int(mon)
   yy = datetime.date.today().strftime("%Y")
   year = int(yy)
   print year

   for state_fips in (4,5,6):
       for year in range(1993, year+1):
           for j in range(1,13):
               yearMonth1 = year,j,state_fips
               yearMonth = year,j
               print yearMonth1
           if (yearMonth) == (year,month):
               break

它将响应打印为:

(1993, 1, 4)
(1993, 2, 4)
(1993, 3, 4)... 
.
.
(1993, 1, 5)
(1993, 2, 5)
(1993, 3, 5)
.
.
(2017, 12, 6)

如何让这个 for 循环在 2017 / 03 结束,即当前的月份和年份,而不是一直到 2017 年底?

首先,您在提取今天的年份和月份时过于复杂。只需使用 datetime.date.today():

返回的 date 对象的 yearmonth 属性
today = datetime.date.today()
# in the loop we'll use (today.year, today.month)

在你的循环中你犯了两个错误:你重复使用了 year(屏蔽了当前年份值),并且你将 if 语句放在年循环中,而不是月循环中,所以后者一直持续到 12。

您必须在 innermost 循环中测试 month 变量,而不是在外部年份循环中,对照正确的当前年份值。外循环在当年自然结束:

today = datetime.date.today()

for state_fips in (4,5,6):
    for year in xrange(1993, today.year + 1):
        for month in xrange(1,13):
            yearMonth1 = year, month, state_fips
            print yearMonth1
            # break out of month loop if this month is reached
            if (year, month) == (today.year, today.month):
                break

当您使用 Python 2 时,我将 range() 调用替换为 xrange() 以避免创建仅用于迭代的列表。

您可以使用 itertools.product function 来生成一个循环:

from itertools import product:

today = datetime.date.today()

years, months = xrange(1993, today.year + 1), xrange(1, 13)
for state_fips, year, month in product((4, 5, 6), years, months):
    yearMonth1 = year, month, state_fips
    print yearMonth1
    # break out of month loop if this month is reached
    if (year, month) == (today.year, today.month):
        break