码迷,mamicode.com
首页 > 编程语言 > 详细

浅谈Python时间模块

时间:2015-12-29 06:17:24      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

浅谈Python时间模块

今天简单总结了一下Python处理时间和日期方面的模块,主要就是datetime、time、calendar三个模块的使用。希望这篇文章对于学习Python的朋友们有所帮助

首先就是模块的调用,很多IDE都已经安装好了很多Python经常使用到的模块,所以我们暂时不需要安装模块了。

1 import datetime
2 import time
3 import calendar

1.获取到此时的准确时间

1 # 获取此时的时间
2 print time.localtime()

输出格式为:

1 time.struct_time(tm_year=2015, tm_mon=12, tm_mday=29, tm_hour=1, tm_min=10, tm_sec=25, tm_wday=1, tm_yday=363, tm_isdst=0)

2.获取当天的日期

1 # 获取当天的日期
2 print datetime.datetime.now()
3 print datetime.date.today()

3.获取昨天的日期

 1 # 获取昨天的日期
 2 def getYesterday():
 3     today = datetime.date.today()
 4     oneday = datetime.timedelta(days=1)
 5     yesterday = today - oneday
 6     print type(today)     # 查看获取到时间的类型
 7     print type(yesterday)
 8     return yesterday
 9 yesterday = getYesterday()
10 print "昨天的时间:", yesterday

4.获取n天以前的日期

。。。这个应该就不用给出代码了吧,稍微想想就可以得出结果了。

5.字符串转换为时间和日期

1 # 字符串转换为时间
2 def strTodatetime(datestr, format):
3     return datetime.datetime.strptime(datestr, format)
4 print time.strftime("%Y-%m-%d", time.localtime())
5 print strTodatetime("2014-3-1","%Y-%m-%d")
6 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
7 print strTodatetime("2005-2-16","%Y-%m-%d")-strTodatetime("2004-12-31","%Y-%m-%d")

输出结果:

1 2015-12-29
2 2014-03-01 00:00:00
3 2015-12-29 01:10:25
4 47 days, 0:00:00

6.获取日历相关信息

 1 # 获取某个月的日历,返回字符串类型
 2 cal = calendar.month(2015, 12)
 3 print cal
 4 calendar.setfirstweekday(calendar.SUNDAY)  # 设置日历的第一天
 5 cal = calendar.month(2015, 12)
 6 print cal
 7 
 8 # 获取一年的日历
 9 cal = calendar.calendar(2015)
10 print cal
11 cal = calendar.HTMLCalendar(calendar.MONDAY)
12 print cal.formatmonth(2015, 12)

7.calendar模块还可以处理闰年的问题

1 # 判断是否闰年、两个年份之间闰年的个数
2 print calendar.isleap(2012)
3 print calendar.leapdays(2010, 2015)

 

浅谈Python时间模块

标签:

原文地址:http://www.cnblogs.com/BaiYiShaoNian/p/5084517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!