2017-05-31 41 views
1

並提前致謝!我有一個我寫的函數,它以「http://www.examplesite.com/'year'+' - '+'month'」的形式生成並附加一個URL到列表中,每個月附加一個給定年份的字符串格式。該函數適用於我正在嘗試做的事情,但我想知道是否有更簡單的方法來使用Python 3的日期時間模塊,可能使用時間變化。簡單的方式與日期時間時間差?

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 
+0

我不知道你使用的年份和月份,但在Python中,你可以使用劃時代的時間哪個更更好的方法做你的東西。 – Gahan

+0

這看起來很直截了當,我只是拋棄for循環的while循環。 –

回答

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 
>>> 
+0

太棒了!謝謝你們的幫助!兩者都工作! –

0

你必須即使使用DateTime對象爲年減1下降:

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

結果是2016年。我想你處理年度途中是不夠好。

只是想簡化月,使用範圍()比硬編碼月列表中的其他:

>>> 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'0'數字填充以產生一個長度寬度的字符串。