python產生日曆執行個體解析

來源:互聯網
上載者:User
本文執行個體展示了Python產生日曆的實現方法。該執行個體可實現一個月的日曆產生5x7的列表,列表裡的沒個日期為datetime類型,採用python內建的 calendar 模組實現。

程式運行結果如下:

python test.py 2014 09 2014-08-31 2014-09-01 2014-09-02 2014-09-03 2014-09-04 2014-09-05 2014-09-06 2014-09-07 2014-09-08 2014-09-09 2014-09-10 2014-09-11 2014-09-12 2014-09-13 2014-09-14 2014-09-15 2014-09-16 2014-09-17 2014-09-18 2014-09-19 2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26 2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03 2014-10-04 

python代碼如下:

#coding:utf-8# Last modified: 2014-08-21 11:08:08 import calendar import datetime import sys  def getcal(y, m):  # 從周日開始  cal = calendar.Calendar(6)  if not isinstance(y, int): y = int(y)  if not isinstance(m, int): m = int(m)  if m == 1: # 1月份   py = y - 1; pm = 12;   ny = y; nm = 2  elif m == 12: # 12月份   py = y; pm = 11   ny = y + 1; nm = 1  else:   py = y; pm = m - 1   ny = y; nm = m + 1  pcal = cal.monthdayscalendar(py, pm) # 上一月  ncal = cal.monthdayscalendar(ny, nm) # 下一月  ccal = cal.monthdayscalendar(y, m)  # 當前  w1 = ccal.pop(0) # 取第一周  w2 = ccal.pop() # 取最後一周  wp = pcal.pop() # 上個月的最後一周  wn = ncal.pop(0) # 下個月的第一周  #r1 = [datetime.date(y, m ,w1[i]) or wp[i] for i in range(7)]  r1 = [w1[i] and datetime.date(y, m, w1[i]) or datetime.date(py, pm, wp[i]) for i in range(7)]  r2 = [w2[i] and datetime.date(y, m, w2[i]) or datetime.date(ny, nm, wn[i]) for i in range(7)]  # 轉datetime  result = []  result.append(r1) # 第一周  for c in ccal:  # 其他周   result.append([datetime.date(y,m,i) for i in c])  result.append(r2) # 最後一周  return result  if __name__ == '__main__':  for w in getcal(sys.argv[1], sys.argv[2]):   for d in w:    print d,   print 

希望本文所述執行個體對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.