python-时间操作
1. 获取当前时间
import time
# 获取当前日期时间 返回值:当前日期时间
def get_now_time():
now = time.localtime()
now_time = time.strftime("%Y-%m-%d %H:%M:%S", now)
return now_time
if __name__ == '__main__':
now_time = get_now_time()
print(now_time)
2. 日期减掉特定时长
import datetime
today=datetime.datetime.now()
datetime1=today-datetime.timedelta(seconds=10) #减10秒
datetime2=today-datetime.timedelta(minutes=10) #减10分钟
datetime3=today-datetime.timedelta(hours=1) #减1小时
datetime4=today-datetime.timedelta(days=1) #减1天
datetime5=today-datetime.timedelta(weeks=1) #减1周
datetime6=today.strftime('%Y-%m-%d') #将时间格式化为字符串
3. 计算2个时间戳之差
import datetime
time1 = datetime.datetime.fromtimestamp(start_time)
time2 = datetime.datetime.fromtimestamp(end_time)
time_diff = time2-time1
print(time_diff)
print(time_diff.total_seconds())
4. 获取文件的修改时间、访问时间、创建时间、大小占用
# -*- coding: UTF8 -*-
import os
import time
def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return time.strftime('%Y-%m-%d %H:%M:%S', timeStruct)
def get_FileCreateTime(filePath):
# '''获取文件的创建时间'''
# filePath = unicode(filePath,'utf8')
t = os.path.getctime(filePath)
return TimeStampToTime(t)
def get_FileModifyTime(filePath):
# '''获取文件的修改时间'''
# filePath = unicode(filePath, 'utf8')
t = os.path.getmtime(filePath)
return TimeStampToTime(t)
def get_FileAccessTime(filePath):
# '''获取文件的访问时间'''
# filePath = unicode(filePath, 'utf8')
t = os.path.getatime(filePath)
return TimeStampToTime(t)
def get_FileSize(filePath):
# '''获取文件的大小,结果保留两位小数,单位为MB'''
fsize = os.path.getsize(filePath)
fsize = fsize / float(1024 * 1024)
return round(fsize, 2)
if __name__ == '__main__':
path = r"/opt/test"
print(get_FileCreateTime(path))
print(get_FileModifyTime(path))
print(get_FileAccessTime(path))
print(get_FileSize(path))