python 之日期时间处理

##python时间操作一般使用time、datetime两个模块

对于time模块,时间的表示模式有3种
1、时间戳:time.time()
2、字符串: time.strftime('%Y%m%d')
3、struct_time格式: time.localtime()

如下所示:

 1 #时间操作
 2 >>> import time
 3 >>> time.time()
 4 1450336566.81052
 5 >>> time.localtime()
 6 time.struct_time(tm_year=2015, tm_mon=12, tm_mday=17, tm_hour=15, tm_min=16, tm_sec=14, tm_wday=3, tm_yday=351, tm_isdst=0)
 7 >>> time.strftime('%Y%m%d %H%M%S')
 8 '20151217 151632'
 9 >>> time.strptime('20151212 121212','%Y%m%d %H%M%S')
10 time.struct_time(tm_year=2015, tm_mon=12, tm_mday=12, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=5, tm_yday=346, tm_isdst=-1)
11 >>> time.mktime(time.localtime())
12 1450336685.0
13 >>> 
14 >>> yesterday = time.strftime('%Y-%m-%d 00:00:00',time.localtime(time.time()-3600*24))
15 >>> print yesterday
16 2015-12-16 00:00:00
17 >>> tomorrow = time.strftime('%Y-%m-%d 00:00:00',time.localtime(time.time()+3600*24))
18 >>> print tomorrow
19 2015-12-18 00:00:00



datetime对于时间计算很有用
datetime模块下有几个比较有用的方法 datetime,date,time,timedelta
语法: datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
date(year, month, day) --> date object
time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
timedelta(days=1,hours=2,minutes=3,seconds=4)
calendar.monthrange(year, month):判断由year和month组成月份,返回该月第一天为周几和该月总共有多少天

 

 1 ##取日期列表
 2 from datetime import datetime,date,timedelta
 3 def get_range_time(begin,end,step):
 4     while begin < end:
 5         yield begin
 6         begin = begin + step
 7 
 8 for i in get_range_time(datetime(2015,11,2),datetime(2016,3,2),timedelta(days=1)):
 9     print i
10 
11 from datetime import datetime,date,timedelta
12 import calendar
13 
14 #取动态月(自然月需要置day=1),如下
15 def get_month_range(startdate = None):
16     if startdate is None:
17         startdate = date.today().replace(day=1)
18     _,days_in_month = calendar.monthrange(startdate.year,startdate.month)
19     enddate = startdate + timedelta(days=days_in_month)
20     return startdate,enddate
21     
22 begin,end = get_month_range()
23 add_step = timedelta(days=1)
24 while begin < end:
25     print begin
26     begin = begin + add_step

 

请记住以下时间转换关系图

 

posted @ 2015-12-18 17:29  benric  阅读(3901)  评论(0编辑  收藏  举报