2015-06-03 37 views
1

我試圖格式化由管道(「|」)分開的一堆日期以用於我正在進行的Web API查詢,在七天內向後計數並將這些日期中的每一個添加到複合字符串中。我閱讀文檔並拼湊在一起,date.today()和datetime.timedelta的組合就是我所需要的。我寫的方法:如何在Python中計算日期?

def someMethod(): 
    ret = '' 
    pythonic_date = datetime.date.today() 
    for i in range(0, 8): 
     pythonic_date -= datetime.timedelta(days=1) 
     ret += "SomePage" + datetime.date.today().strftime("%B" + " ") 
     ret += str(pythonic_date.day).lstrip('0') 
     ret += ", " + str(pythonic_date.year) + "|" 
    ret = ret[0:len(ret) - 1] 
    return ret 

我希望得到以下的輸出:

SomePage的/ 2015年6月2日|添加SomePage/2015年6月1日|添加SomePage/2015年5月31日|添加SomePage /月30,2015年|添加SomePage/2015年5月29日|添加SomePage/2015年5月28日|添加SomePage/2015年5月27日|添加SomePage/2015年5月26日

相反,我得到以下輸出:

SomePage/June 2,2015 | SomePage/2015年6月1日| SomePage/June 31,2015 | SomePage/June 30,2015 | SomePage/June 29,2015 | SomePage/June 28,2015 | SomePage/June 27,2015 | SomePage的/ 2015年6月26日

我看到的,而不是對整個日期運行,使用timedelta這裏只是天真地循環迴天日期字段中的類的對象。我有兩個問題:

  1. 爲什麼這樣實現?
  2. 我該怎麼做才能得到我想要的?

編輯:第二次看,我寫的函數甚至無法處理幾年之間的移動。嚴重的是,這樣做的更好方法是什麼?日期時間文檔(https://docs.python.org/3/library/datetime.html#datetime.timedelta.resolution)是荒謬的密集。

回答

5

不,這根本不是什麼時間節奏。它完全符合你的期望。

錯誤只是在您的代碼中:您總是打印從datetime.date.today()而不是從pythonic_date的月份。

一個更好的打印格式的日期的方式是使用一個調用strftime

ret += "SomePage" + pythonic_date.strftime("%B %-d, %Y") + "|" 
+0

相依:['%-d'(格式爲短劃線)](http://stackoverflow.com/q/28894172/4279)不支持所有系統。另外,OP可以使用列表:'lst.append(「SomePage/{:%B%d,%Y}」.format(pythonic_date))'和'return「|」.join(lst)'結尾。 – jfs

+0

我不知道在前面添加「 - 」會刪除前導零,但看到該解決方案不是平臺不可知的,它不是我*將要使用的技巧。 這就是說,你發現了一個愚蠢的錯誤,我應該看到審查:謝謝! –

1

你可以考慮使用arrow處理日期,它會讓你的生活更輕鬆。

import arrow 

def someMethod(): 
    fulldates = [] 
    for date in [arrow.now().replace(days=-i) for i in range(0, 8)]: 
     fulldates.append("SomePage/{fmtdate}".format(fmtdate=date.format("MMM D, YYYY"))) 
    return '|'.join(fulldates) 

print(someMethod()) 

輸出是

SomePage/Jun 3, 2015|SomePage/Jun 2, 2015|SomePage/Jun 1, 2015|SomePage/May 31, 2015|SomePage/May 30, 2015|SomePage/May 29, 2015|SomePage/May 28, 2015|SomePage/May 27, 2015 
+0

這個答案缺少一件事:我也需要以某種方式切斷白天領域的前導零。 –

+0

我編輯的代碼,以便沒有前導零,輸出也更新 – WoJ