從本月起算 過去 12 個月月份 python

2021-09-26 13:04:21 字數 1811 閱讀 6708

爬**時有段資料需要生成過去12個月月份起始時間,拼接url. 需求如下

[

'2019-7-1|2019-7-31'

,'2019-6-1|2019-6-30'

,'2019-5-1|2019-5-31'

,'2019-4-1|2019-4-30'

,'2019-3-1|2019-3-31'

,'2019-2-1|2019-2-28'

,'2019-1-1|2019-1-31'

,'2018-12-1|2018-12-31'

,'2018-11-1|2018-11-30'

,'2018-10-1|2018-10-31'

,'2018-9-1|2018-9-30'

,'2018-8-1|2018-8-31'

]

**如下

import calendar

from datetime import datetime, timedelta

def make_last_12_month()

:"""

生成過去12個月的時間字串列表

['2019-6-1|2019-6-30'

,'2019-5-1|2019-5-31'

,'2019-4-1|2019-4-30'

...]

""" days = datetime.

now(

).day

last_month = datetime.

now()-

timedelta

(days=days)

time_li =

for i in

range(12

):d = calendar.

monthrange

(last_month.year, last_month.month)

tm =

'{}-{}-{}|{}-{}-{}'

.format

(last_month.year, last_month.month,

1, last_month.year, last_month.month, d[1]

) last_month = last_month -

timedelta

(days=d[1]

) time_li.

(tm)

print

(time_li)

return time_li

順便貼個生成過去 90 天的 codes

def make_last_90_day()

:"""

生成過去 90 天日期列表 [

'2019-07-22|2019-07-22'

,'2019-07-21|2019-07-21'

...]

""" days=

for day in

range(1

,91):

get_time = datetime.

now()-

timedelta

(days=day)

get_time = get_time.

strftime

('%y-%m-%d'

) get_time = f'|'

days.

(get_time)

return days