1. 程式人生 > >python 時間格式 及 轉換 檔案時間說明

python 時間格式 及 轉換 檔案時間說明

#coding: utf-8
__author__ = 'KK'
import time

#獲取當前時間的字串形式 Wed Sep 06 20:14:46 2017
print time.ctime()
#獲取當前時間戳 1504700086.44
print time.time()
#當前時間的struct_time格式 time.struct_time(tm_year=2017, tm_mon=9, tm_mday=6, tm_hour=20, tm_min=14, tm_sec=46, tm_wday=2, tm_yday=249, tm_isdst=0)
print time.localtime()
# 當前時間格式化為字串 2017_09_06 20:14:46
print time.strftime("%Y_%m_%d %H:%M:%S")
時間轉換:
import os
import time
import datetime
#獲取檔案的建立時間
file ="D:\\log.txt"
timestamp = os.path.getmtime(file)
#1504700941.93
print timestamp
#time.struct_time(tm_year=2017, tm_mon=9, tm_mday=6, tm_hour=20, tm_min=29, tm_sec=1, tm_wday=2, tm_yday=249, tm_isdst=0)
print time.localtime(timestamp) #2017-09-06 20:29:01.934336 print datetime.datetime.fromtimestamp(timestamp) #2017-09-06 print datetime.date.fromtimestamp(timestamp) #time.struct_time(tm_year=2017, tm_mon=9, tm_mday=6, tm_hour=12, tm_min=29, tm_sec=1, tm_wday=2, tm_yday=249, tm_isdst=0) print time.gmtime(os.path.getmtime(file))

#檔案時間說明:
print os.path.getatime(file) #輸出最近訪問時間1504700920.69 win2003 SP1之後出於效能考慮該引數禁用,=建立時間
print os.path.getctime(file) #輸出檔案建立時間1504700920.69
print os.path.getmtime(file) #輸出最近修改時間1504705313.16
print time.gmtime(os.path.getmtime(file)) #以struct_time形式輸出最近修改時間
print os.path.getsize(file) #輸出檔案大小(位元組為單位)
print os.path.abspath(file) #輸出絕對路徑'/Volumes/Leopard/Users/Caroline/Desktop/1.mp4'
print os.path.normpath(file) #輸出規範化路徑'/Volumes/Leopard/Users/Caroline/Desktop/1.mp4'