python 获取过去几天,过去几个月,过去几年的时间列表

在平时的开发中,需要获取最近几个月,最近几年或者最近几天的时间列表,本文使用了arrow去实现了这几个过程。

    def get_day(num):
        day_list = []
        a = arrow.now()  # 当前本地时间
        for i in range(0, num + 1):
            yearmonth = a.shift(days=-i).format("YYYY-MM-DD")
            day_list.append(yearmonth)
        return day_list
    
    print(get_day(10))
    
    def get_month(num):
        month_list = []
        a = arrow.now()  # 当前本地时间
        for i in range(0,num+1):
            yearmonth = a.shift(months=-i).format("YYYYMM")
            month_list.append(yearmonth)
        return month_list
    print(get_month(10))

    def get_year(num):
        year_list = []
        a = arrow.now()  # 当前本地时间
        for i in range(0,num+1):
            year = a.shift(years=-i).format("YYYY")
            year_list.append(year)
        return year_list
    print(get_year(10))

输出结果

  

C:\Python37\python3.exe D:/shannanai_spider/test/test.py
['2021-05-29', '2021-05-28', '2021-05-27', '2021-05-26', '2021-05-25', '2021-05-24', '2021-05-23', '2021-05-22', '2021-05-21', '2021-05-20', '2021-05-19']
['202105', '202104', '202103', '202102', '202101', '202012', '202011', '202010', '202009', '202008', '202007']
['2021', '2020', '2019', '2018', '2017', '2016', '2015', '2014', '2013', '2012', '2011']

Process finished with exit code 0

 

posted @ 2021-05-29 11:23  淋哥  阅读(1100)  评论(0编辑  收藏  举报