2013年11月4日 星期一

Python 2.7 進行 datetime 加減(timedalta)及設定輸出格式(strftime)


  1. 設定 someday = datetime.date(2013,10,28)
  2. datetime.timedelta(days = 1) 用於計算 datetime 時間增減(本例:以1天為單位)
  3. 可利用 strftime("%Y%m%d) datetime 控制輸出格式

vi test.py
import time
import datetime

someday = datetime.date(2014,9,20)

while (someday <= datetime.date.today()) :
    # print out with date format : YYYYMMDD, example : 20140920
    print str(someday.strftime("%Y%m%d"))
    someday += datetime.timedelta(days = 1)

print "================="
    
someday = datetime.date.today()

while (someday >= datetime.date(2014,9,15)) :
    # print out with date format : YYYYMMDD, example : 2014-09-20
    print str(someday.strftime("%Y-%m-%d"))
    # minus, timedelta(days = 1)
    someday -= datetime.timedelta(days = 1)

print "================="

someday = datetime.date.today()

while (someday >= datetime.date(2014,9,15)) :
    # print out with date format : YYYYMMDD, example : 2014/09/20
    print str(someday.strftime("%Y/%m/%d"))
    # add, timedelta(days = -1)
    someday += datetime.timedelta(days = -1)

執行結果:
$ python test.py
20140920
20140921
20140922
=================
2014-09-22
2014-09-21
2014-09-20
2014-09-19
2014-09-18
2014-09-17
2014-09-16
2014-09-15
=================
2014/09/22
2014/09/21
2014/09/20
2014/09/19
2014/09/18
2014/09/17
2014/09/16
2014/09/15

延伸閱讀:datetime - Basic date and time types (python.org)

#

沒有留言: