浅谈Python时间模块

浅谈Python时间模块学习

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

首先就是模块的调用,不少IDE都已经安装好了不少Python常用到的模块,因此咱们暂时不须要安装模块了。code

1 import datetime 2 import time 3 import calendar

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

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

输出格式为:blog

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.获取昨天的日期get

 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天之前的日期form

。。。这个应该就不用给出代码了吧,稍微想一想就能够得出结果了。class

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

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)
相关文章
相关标签/搜索