Python 按當前日期(年、月、日)建立多級目錄的方法

來源:互聯網
上載者:User

標籤:cal   exists   圖片   其他   日誌   Oday   檔案中   src   .com   

 

先看實際效果,現在時間2018.4.26

 

使用python指令碼按照年月日產生多級目錄,建立的目錄可以將系統產生的記錄檔放入其中,方便查閱,代碼如下:

#!/usr/bin/env python#coding=utf-8import timeimport os#獲得當前系統時間的字串localtime=time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time()))print(‘localtime=‘+localtime)#系統目前時間年份year=time.strftime(‘%Y‘,time.localtime(time.time()))#月份month=time.strftime(‘%m‘,time.localtime(time.time()))#日期day=time.strftime(‘%d‘,time.localtime(time.time()))#具體時間 小時分鐘毫秒mdhms=time.strftime(‘%m%d%H%M%S‘,time.localtime(time.time()))fileYear=os.getcwd()+‘/upload_files/‘+‘/‘+yearfileMonth=fileYear+‘/‘+monthfileDay=fileMonth+‘/‘+dayif not os.path.exists(fileYear):    os.mkdir(fileYear)    os.mkdir(fileMonth)    os.mkdir(fileDay)else:    if not os.path.exists(fileMonth):        os.mkdir(fileMonth)        os.mkdir(fileDay)    else:        if not os.path.exists(fileDay):            os.mkdir(fileDay)#建立一個檔案,以‘timeFile_’+具體時間為檔案名稱fileDir=fileDay+‘/timeFile_‘+mdhms+‘.txt‘out=open(fileDir,‘w‘)#在該檔案中寫入當前系統時間字串out.write(‘localtime=‘+localtime)out.close()

 

關於日期時間的其他知識點

import datetimetoday = datetime.date.today()

想要指定到時分秒的話可以搞成這樣

import datetime#這就是指定 2008/12/5 23:59:59today = datetime.datetime(2008, 12, 5, 23, 59, 59) #datetime 也可以這樣做加減,一次加一秒x = datetime.timedelta(seconds = 1)y = datetime.date(2008, 12, 5, 23, 59, 59)w = x + y#w = datetime.datetime(2008, 12, 6, 0, 0) #一次加 23小時 59分 59秒x = datetime.timedelta(hours = 23, minutes = 59, seconds = 59)w = w + x#w = datetime.datetime(2008, 12, 6, 23, 59, 59) 

還有就是,如果想要拿到今天的年,月,日 也是很簡單的說

import datetimex = datetime.datetime.now() #現在時間#x = datetime.datetime(2008, 12, 5, 23, 59, 59) #指定時間x.year #會拿到 2008x.month #會拿到 12x.day # 會拿到 5x.hour   #時x.minute #分x.second #秒 59 

 

Python 按當前日期(年、月、日)建立多級目錄的方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.