python生成日历实例解析

作者:shichen2014 时间:2023-05-16 12:47:31 

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

标签:python,生成,日历
0
投稿

猜你喜欢

  • 倾斜的鼠标翻转导航制作上的烦恼

    2007-06-20 16:39:00
  • Python Pygame实现落球游戏详解

    2021-06-23 00:54:38
  • python 实现全球IP归属地查询工具

    2023-10-05 16:31:33
  • Lost connection to MySQL server at 'reading authorization packet', system error: 0

    2024-01-20 19:06:26
  • 使用sql语句创建和删除约束示例代码

    2024-01-15 21:55:51
  • asp 过滤尖括号内所有内容的正则代码

    2011-04-03 10:40:00
  • python 实现定时任务的四种方式

    2023-06-28 14:37:27
  • 浅析Python 中整型对象存储的位置

    2021-10-06 13:40:20
  • Mysql动态更新数据库脚本的示例讲解

    2024-01-23 11:22:49
  • Pandas数值排序 sort_values()的使用

    2023-02-21 01:12:02
  • Flash的Fallback Content等

    2010-04-01 12:18:00
  • OpenCV实现常见的四种图像几何变换

    2022-11-08 11:20:50
  • 有效的提高编程技能的12个方法

    2023-07-15 09:11:40
  • pip安装提示Twisted错误问题(Python3.6.4安装Twisted错误)

    2021-09-26 04:05:50
  • 详细分析Python collections工具库

    2022-06-28 01:18:57
  • 发一新浪招聘的图片滚动控制JS效果

    2011-08-10 19:17:25
  • javascript获取select的当前值示例代码(兼容IE/Firefox/Opera/Chrome)

    2024-04-22 12:49:59
  • Python提高运行速度工具之Pandarallel的使用教程

    2021-07-16 20:14:09
  • Python中利用sorted()函数排序的简单教程

    2022-09-13 20:26:36
  • python实现图片上添加图片

    2022-01-13 19:19:05
  • asp之家 网络编程 m.aspxhome.com