python時間處理詳解

來源:互聯網
上載者:User
1.擷取目前時間的兩種方法:

import datetime,timenow = time.strftime("%Y-%m-%d %H:%M:%S")print nownow = datetime.datetime.now()print now

2.擷取上個月最後一天的日期(本月的第一天減去1天)

last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)print last

3.擷取時間差(時間差單位為秒,常用於計算程式啟動並執行時間)

starttime = datetime.datetime.now()#long runningendtime = datetime.datetime.now()print (endtime - starttime).seconds

4.計算目前時間向後10個小時的時間

d1 = datetime.datetime.now()d3 = d1 + datetime.timedelta(hours=10)d3.ctime()

其本上常用的類有:datetime和timedelta兩個。它們之間可以相互加減。每個類都有一些方法和屬性可以查看具體的值,如 datetime可以查看:天數(day),小時數(hour),星期幾(weekday())等;timedelta可以查看:天數(days),秒數 (seconds)等。

5.python中時間日期格式化符號:

%y 兩位元的年份表示(00-99)

%Y 四位元的年份表示(000-9999)

%m 月份(01-12)

%d 月內中的一天(0-31)

%H 24小時制小時數(0-23)

%I 12小時制小時數(01-12)

%M 分鐘數(00=59)

%S 秒(00-59)


%a 本地簡化星期名稱

%A 本地完整星期名稱

%b 本地簡化的月份名稱

%B 本地完整的月份名稱

%c 本地相應的日期表示和時間表示

%j 年內的一天(001-366)

%p 本地A.M.或P.M.的等價符

%U 一年中的星期數(00-53)星期天為星期的開始

%w 星期(0-6),星期天為星期的開始

%W 一年中的星期數(00-53)星期一為星期的開始

%x 本地相應的日期表示

%X 本地相應的時間表示

%Z 當前時區的名稱

%% %號本身

附上範例程式碼:

代碼Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->#-*-coding:utf-8-*-

import datetime, calendar

def getYesterday():       today=datetime.date.today()       oneday=datetime.timedelta(days=1)       yesterday=today-oneday      return yesterday
def getToday():       return datetime.date.today()

#擷取給定參數的前幾天的日期,返回一個list

def getDaysByNum(num):        today=datetime.date.today()        oneday=datetime.timedelta(days=1)            li=[]            for i in range(0,num):           #今天減一天,一天一天減            today=today-oneday           #把日期轉換成字串           #result=datetostr(today)            li.append(datetostr(today))       return li     #將字串轉換成datetime類型   def strtodatetime(datestr,format):           return datetime.datetime.strptime(datestr,format)     #時間轉換成字串,格式為2008-08-02   def datetostr(date):         return    str(date)[0:10]     #兩個日期相隔多少天,例:2008-10-03和2008-10-01是相隔兩天   def datediff(beginDate,endDate):        format="%Y-%m-%d";        bd=strtodatetime(beginDate,format)        ed=strtodatetime(endDate,format)            oneday=datetime.timedelta(days=1)        count=0      while bd!=ed:            ed=ed-oneday            count+=1      return count     #擷取兩個時間段的所有時間,返回list   def getDays(beginDate,endDate):        format="%Y-%m-%d";        bd=strtodatetime(beginDate,format)        ed=strtodatetime(endDate,format)        oneday=datetime.timedelta(days=1)        num=datediff(beginDate,endDate)+1        li=[]       for i in range(0,num):            li.append(datetostr(ed))            ed=ed-oneday       return li     #擷取當前年份 是一個字串   def getYear():       return str(datetime.date.today())[0:4]     #擷取當前月份 是一個字串   def getMonth():       return str(datetime.date.today())[5:7]     #擷取當前天 是一個字串   def getDay():       return str(datetime.date.today())[8:10]      def getNow():       return datetime.datetime.now()     print getToday()   print getYesterday()   print getDaysByNum(3)   print getDays('2008-10-01','2008-10-05')   print '2008-10-04 00:00:00'[0:10]     print str(getYear())+getMonth()+getDay()   print getNow()
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.