初学 Python — 处理日期与时间[0]
2014-10-27 10:42
543 查看
4000
一、寻找2013年与2014今日之前(包括今日)年所有的星期五
*注意
1 today.year,today.month,today.day,today.weekday()返回的都是int型,其中weekday()的周一到周日分别以0-6表示。
2 默认日期格式是2014-03-04
3 切不可使用这种循环 while today.year==2014 or 2013。同时Python逻辑运算符号没有||,&&一说。
4 如果要寻找某年的某月的星期X,则定义以下函数(不考虑鲁棒性)
需加入模块名限定即可
一、寻找2013年与2014今日之前(包括今日)年所有的星期五
import datetime import calendar today = datetime.date.today() oneday = datetime.timedelta(days=1) while today.year == 2014 or today.year == 2013: if today.weekday()==4: print(today.strftime('%A, %d-%b-%Y')) today = today-oneday*7 else: today -= oneday
*注意
1 today.year,today.month,today.day,today.weekday()返回的都是int型,其中weekday()的周一到周日分别以0-6表示。
2 默认日期格式是2014-03-04
3 切不可使用这种循环 while today.year==2014 or 2013。同时Python逻辑运算符号没有||,&&一说。
4 如果要寻找某年的某月的星期X,则定义以下函数(不考虑鲁棒性)
import datetime import calendar def FindWeekday(year,month,weekday): oneday = datetime.timedelta(days=1) if month == 0: fristday = datetime.date(year,1,1) while fristday.year == year: if fristday.weekday()==weekday-1: print(fristday.strftime('%A, %d-%b-%Y')) fristday += oneday*7 else: fristday += oneday else: fristday = datetime.date(year,month,1) while fristday.year == year and fristday.month == month: if fristday.weekday()==weekday-1: print(fristday.strftime('%A, %d-%b-%Y')) fristday += oneday*7 else: fristday += oneday5 为了能够随时调用4中函数,我们将其存储到C:/MyPython目录下,建立新文件,载入该模块
import sys sys.path.append("C:\MyPython") #将目标路径加入到Python搜索路径中去 import FindWeekDay #或者 from MyPython import <span style="font-family: Arial, Helvetica, sans-serif;">FindWeekDay </span>这时,如果直接调用
FindWeekDay(2013,1,3)将会报错,TypeError: 'module' object is not callable
需加入模块名限定即可
FindWeekDay.FindWeekDay(2013,1,3)运行结果如下
Wednesday, 02-Jan-2013 Wednesday, 09-Jan-2013 Wednesday, 16-Jan-2013 Wednesday, 23-Jan-2013 Wednesday, 30-Jan-2013
相关文章推荐
- 初学 Python — 处理日期与时间[1]
- python 时间日期处理汇集
- python时间,日期,时间戳处理
- Python实用日期时间处理方法汇总
- PYTHON-基础-时间日期处理小结
- 在Python中处理日期和时间的基本知识点整理汇总
- python datetime 时间日期处理小结
- Python实用日期时间处理方法汇总
- python学习笔记十五:日期时间处理笔记
- Python中基本的日期时间处理的学习教程
- python中关于日期时间处理的问答集锦
- Python模块学习 ---- time 日期时间处理
- python datetime 时间日期处理小结
- python时间和日期处理整理
- 【转】python datetime时间日期处理
- python 时间日期处理汇集
- python 处理日期时间 格式化等
- python 日期时间处理
- python 日期时间处理
- Python datetime时间日期处理