Python 常用函数-最新文件-日期均值-硬盘空间

获取文件夹中最新文件

def get_latest_folder(path):
    try:
        lists = os.listdir(path)         # 列出目录的下所有文件和文件夹保存到lists
        lists.sort(key=lambda fn: os.path.getmtime(path + "/" + fn)) # 按时间排序
        file_new = os.path.join(path, lists[-1])      # 获取最新的文件保存到file_new
        print('In path {} the latest folder is {}'.format(path, file_new))
    except Exception as Err:
        print("Exception Reason: '{}'".format(str(Err)))
    finally:
        return file_new

毫秒级日期求平均值

import time
import datetime

d = ['00:48:53.786', '00:48:53.859']
t = []
sum_t = 0

for i in d:
    # +datatime 的原因是转换出来的时间戳小于系统的初始时间
    # 先将日期转换为毫秒级时间戳放到list中
    dd = datetime.datetime.strptime(i, '%H:%M:%S.%f') + datetime.timedelta(days=36500) 
    ts = int(time.mktime(dd.timetuple()) * 1000.0 + (dd.microsecond / 1000.0))
    t.append(ts)

for i in t:
    # 将时间戳相加求平均值
    sum_t = sum_t + int(i)
    mean_t = sum_t / len(t)


# 再将时间戳转换为日期
mean_t = datetime.datetime.fromtimestamp(mean_t/1000)
print(mean_t.strftime("%H:%M:%S.%f"))

shutil 读取硬盘可用空间

import shutil

path = r'C:'
gb = 1024 ** 3 #GB == gigabyte 
total, used, free  = shutil.disk_usage(path)
total = total // gb
used = used // gb
free = free // gb
print("Total: %d GB" % total )
print("Used: %d GB" % used )
print("Free: %d GB" % free)
posted @ 2022-10-26 13:21  可乐芬达  阅读(50)  评论(0编辑  收藏  举报