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

 

請記住以下時間轉換關系圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM