本文实例展示了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程序设计有所帮助。

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
