写个记录电脑使用时长的脚本

wen 实用脚本 1

本文目录导读:

写个记录电脑使用时长的脚本

  1. Windows 批处理版本
  2. Python 完整版本(推荐)
  3. 使用方法

我来帮你写一个记录电脑使用时长的脚本,这里提供两个版本:一个简单的Windows批处理版本和一个功能更完整的Python版本。

Windows 批处理版本

@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
:: 设置日志文件路径
set LOGFILE=%USERPROFILE%\Desktop\电脑使用记录.log
set DATAFILE=%USERPROFILE%\Desktop\usage_data.txt
:: 如果数据文件不存在,创建初始记录
if not exist "%DATAFILE%" (
    echo 0> "%DATAFILE%"
)
:: 获取当前日期和时间
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do set current_date=%%a%%b%%c
for /f "tokens=1-2 delims=:" %%a in ('time /t') do set current_time=%%a:%%b
:: 记录开机时间
echo.
echo ========================================
echo        电脑使用时间记录系统
echo ========================================
echo 开机时间: %date% %time%
echo 当前时间: %current_date% %current_time%
echo.
:: 显示今日已用时间
set total_minutes=0
if exist "%DATAFILE%" (
    for /f %%a in ('type "%DATAFILE%"') do set total_minutes=%%a
)
:: 计算使用时间(这里简化处理,假设每天记录)
set /a hours=total_minutes/60
set /a minutes=total_minutes%%60
echo 今日累计使用时间: !hours!小时 !minutes!分钟
echo.
echo 记录已保存到: %LOGFILE%
:: 将记录写入日志
echo [%date% %time%] 开机使用记录 >> "%LOGFILE%"
timeout /t 10 >nul
exit

Python 完整版本(推荐)

import time
import datetime
import os
import json
from pathlib import Path
class UsageTracker:
    def __init__(self):
        # 设置存储文件路径
        self.base_dir = Path.home() / "电脑使用记录"
        self.base_dir.mkdir(exist_ok=True)
        self.data_file = self.base_dir / "usage_data.json"
        self.log_file = self.base_dir / "usage_log.txt"
        self.load_data()
    def load_data(self):
        """加载持久化数据"""
        if self.data_file.exists():
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    self.data = json.load(f)
            except:
                self.data = {}
        else:
            self.data = {}
    def save_data(self):
        """保存数据"""
        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(self.data, f, ensure_ascii=False, indent=2)
    def record_daily_usage(self):
        """记录每日使用情况"""
        today = datetime.date.today().isoformat()
        current_time = datetime.datetime.now()
        # 如果今天还没有记录,初始化
        if today not in self.data:
            self.data[today] = {
                "first_seen": current_time.isoformat(),
                "last_seen": current_time.isoformat(),
                "total_minutes": 0,
                "sessions": []
            }
        else:
            # 计算上次会话持续时间
            last_seen = datetime.datetime.fromisoformat(self.data[today]["last_seen"])
            time_diff = current_time - last_seen
            # 如果间隔时间合理(不超过5分钟),则累计
            if time_diff.total_seconds() < 300:  # 5分钟间隔
                additional_minutes = time_diff.total_seconds() / 60
                self.data[today]["total_minutes"] += additional_minutes
                self.data[today]["last_seen"] = current_time.isoformat()
            else:
                # 新会话开始
                self.data[today]["sessions"].append({
                    "start": current_time.isoformat(),
                    "end": current_time.isoformat()
                })
                self.data[today]["first_seen"] = self.data[today].get("first_seen", current_time.isoformat())
                self.data[today]["last_seen"] = current_time.isoformat()
        self.save_data()
        self.write_log(today, current_time)
    def write_log(self, today, current_time):
        """写入日志文件"""
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(f"[{current_time.strftime('%Y-%m-%d %H:%M:%S')}] 使用记录已更新\n")
    def get_daily_report(self, days=7):
        """获取最近几天的使用报告"""
        report_lines = []
        report_lines.append("=" * 50)
        report_lines.append("        电脑使用时间报告")
        report_lines.append("=" * 50)
        report_lines.append("")
        all_days = sorted(self.data.keys(), reverse=True)[:days]
        for day in all_days:
            if day in self.data:
                minutes = self.data[day]["total_minutes"]
                hours = int(minutes // 60)
                mins = int(minutes % 60)
                report_lines.append(f"{day}: {hours}小时{mins:02d}分钟")
        return "\n".join(report_lines)
    def run_monitor(self, interval=60):
        """运行监控(每60秒检查一次)"""
        print("开始监控电脑使用时间...")
        print("按 Ctrl+C 停止监控")
        print("=" * 50)
        try:
            while True:
                self.record_daily_usage()
                time.sleep(interval)  # 每60秒记录一次
        except KeyboardInterrupt:
            print("\n监控已停止")
            print(self.get_daily_report())
            print(f"数据保存在: {self.data_file}")
# 菜单式界面
def main():
    tracker = UsageTracker()
    while True:
        print("\n" + "=" * 50)
        print("        电脑使用时间记录系统")
        print("=" * 50)
        print("1. 开始实时监控")
        print("2. 查看使用报告")
        print("3. 手动记录当前使用")
        print("4. 退出")
        print("=" * 50)
        choice = input("请选择操作 (1-4): ").strip()
        if choice == "1":
            tracker.run_monitor()
        elif choice == "2":
            days = input("查询最近几天 (默认7天): ").strip() or "7"
            print("\n" + tracker.get_daily_report(int(days)))
        elif choice == "3":
            tracker.record_daily_usage()
            print("记录成功!")
        elif choice == "4":
            print("再见!")
            break
        else:
            print("无效选择,请重试")
if __name__ == "__main__":
    main()

使用方法

Python版本:

python usage_tracker.py

主要功能:

  1. 实时监控 - 自动记录使用时间
  2. 使用报告 - 查看每日/近期的使用统计
  3. 数据持久化 - 数据保存在用户目录下

可选增强功能:

# 添加系统托盘图标版本(需要安装 pystray)
def run_with_tray():
    """系统托盘版本"""
    try:
        import pystray
        from PIL import Image
        def on_exit(icon, item):
            tracker.save_data()
            icon.stop()
        # 简单的图标(可以替换为自定义图标)
        image = Image.new('RGB', (64, 64), color='blue')
        menu = pystray.Menu(
            pystray.MenuItem("显示报告", lambda: print(tracker.get_daily_report())),
            pystray.MenuItem("退出", on_exit)
        )
        icon = pystray.Icon("电脑使用记录", image, "电脑使用记录", menu)
        icon.run()
    except ImportError:
        print("需要安装 pystray: pip install pystray")

这些脚本会自动记录你的电脑使用时间,数据保存在用户目录下的"电脑使用记录"文件夹中,你可以根据需要调整监控间隔时间(默认60秒)和报告天数。

抱歉,评论功能暂时关闭!