日期时间增量的简单方法是什么?

时间:2017-05-31 03:33:41

标签: python python-3.x datetime

并提前致谢!我有一个我写的函数生成并以“http://www.examplesite.com/'年'+' - '+'月''的形式将一个网址附加到列表中,为每个添加给定年份的字符串格式月。该函数适用于我正在尝试的功能,但我想知道是否有一种更简单的方法可以使用Python 3的datetime模块,可能使用时间增量。

    source = 'https://www.examplesite.com/'
    year = 2017
    month = ['12', '11', '10', '09', '08', '07', '06', '05', '04', '03', '02', '01']

    while year >= 1989:
        for entry in month:
            page = source + str(year) + '-'  entry
            pageRepository.append(page)
        year -= 1

2 个答案:

答案 0 :(得分:0)

即使使用datetime对象,您也必须减1才能减少年份:

>>> from datetime import date
>>> print date.today().year - 1

结果是2016年。我认为你处理年份的方式已经足够了。

只想简化月份,使用除硬编码月份列表之外的range():

>>> for month in range(12,0,-1):
...     str(month).zfill(2)
...
'12'
'11'
'10'
'09'
'08'
'07'
'06'
'05'
'04'
'03'
'02'
'01'

<强> str.zfill(宽度):

  

返回一个用ASCII&#39; 0&#39;填充的字符串副本。数字,以形成一个长度为宽度的字符串。

答案 1 :(得分:0)

Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)
>>> import datetime
>>> for year in range(1989, datetime.datetime.utcnow().year + 1):
...     for month in range(1, 13):
...             print('{:%Y-%m}'.format(datetime.datetime(year, month, 1)))
...
1989-01
1989-02
1989-03
1989-04
1989-05
...
2017-11
2017-12
>>>