我需要获取过去12个月中每个月的所有日子的文章,但是我的月份和年份都错了吗?

时间:2019-04-02 02:17:23

标签: python-3.x

我从Wiki获得数据,并计算了几个月和几年(2019年,2018年)以查看热门文章。 (过去12个月中每个月的所有天数)。问题是它向我显示了错误的月份??

def get_current_year_month():

    all_data_list = []
    current_date = datetime.now()
    current_month = current_date.month
    current_year = str(current_date.year)
    current_year = current_year[-1:]

    for month in range(current_month, current_month + 12):
        if month > 12:
            year = current_year
            month = current_month - 12
        else:
            year = int(current_year) - 1
        if month < 10:
            month = "0" + str(current_month)

        data = f"https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikisource/all-access/201{year}/{month}/all-days"
        all_data_list.append(data)
        print(data)
    return all_data_list

1 个答案:

答案 0 :(得分:2)

您的错误在month = "0" + str(current_month)行中。必须为month = "0" + str(month)。与month = current_month - 12相同。

完成更正的代码:

def get_current_year_month():
    current_date = datetime.datetime.now()
    current_month = current_date.month
    all_data_list = []
    for month in range(current_month, current_month + 12):
        year = current_date.year - (month <= 12)
        month = "{:02d}".format((month - 1) % 12 + 1)
        data = f"https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikisource/all-access/{year}/{month}/all-days"
        all_data_list.append(data)
    return all_data_list