如何实现文件最后修改后时长输出?哪种开发语言更便捷?
实现文件修改后经过时间的方案
一、Batch脚本的局限性
Batch本身没有原生的日期时间差计算能力,要实现这个需求需要做大量字符串解析和手动计算,还要适配不同系统的日期格式,容易出bug,不推荐用Batch完成这个需求。
二、更适合的语言推荐
1. PowerShell(Windows原生,推荐)
PowerShell基于.NET框架,能直接调用日期时间相关的API,代码简洁可靠,完全适配你的需求:
$targetFile = "my file.txt" $logFile = ".\Logs\my file.txt" $lastUpdateTime = (Get-Item $targetFile).LastWriteTime $timeElapsed = New-TimeSpan -Start $lastUpdateTime -End (Get-Date) $result = "`"$targetFile`" was updated $($timeElapsed.Hours) hours $($timeElapsed.Minutes) minutes $($timeElapsed.Seconds) seconds ago" $result | Out-File -FilePath $logFile -Encoding utf8
这段代码自动处理跨天、跨月的时间差,无需手动计算,输出格式完全符合要求。
2. Python(跨平台,多系统通用)
如果需要在Windows、Linux、macOS等多平台运行,Python是更好的选择,语法简洁易维护:
import os import time target_file = "my file.txt" log_path = ".\\Logs\\my file.txt" # 获取文件最后修改时间戳(秒) last_modified = os.path.getmtime(target_file) current_time = time.time() diff_seconds = int(current_time - last_modified) # 转换为时、分、秒 hours = diff_seconds // 3600 minutes = (diff_seconds % 3600) // 60 seconds = diff_seconds % 60 # 生成输出内容并写入日志 output = f'"{target_file}" was updated {hours} hours {minutes} minutes {seconds} seconds ago' with open(log_path, 'w', encoding='utf-8') as f: f.write(output)
三、硬要用Batch实现的方案(不推荐)
如果必须基于Batch开发,可借助wmic工具获取时间戳,手动计算时间差,示例代码如下(仅适用于Windows,需处理路径转义):
@echo off setlocal enabledelayedexpansion set "targetFile=my file.txt" set "logFile=.\Logs\my file.txt" :: 获取文件修改时间戳并转换为秒(UTC) for /f "skip=1 tokens=2 delims==" %%a in ('wmic datafile where name^="%targetFile:\=\\%" get lastmodified /value') do set "lastMod=%%a" set "lastSec=!lastMod:~0,14!" set /a lastSec=!lastSec! / 10000000 :: 获取当前时间戳并转换为秒(UTC) for /f "skip=1 tokens=2 delims==" %%a in ('wmic os get localdatetime /value') do set "current=%%a" set "currentSec=!current:~0,14!" set /a currentSec=!currentSec! / 10000000 :: 计算时间差并转换为时、分、秒 set /a diffSec=currentSec - lastSec set /a hours=diffSec / 3600 set /a remaining=diffSec %% 3600 set /a minutes=remaining / 60 set /a seconds=remaining %% 60 :: 写入日志文件 echo "%targetFile%" was updated %hours% hours %minutes% minutes %seconds% seconds ago > "%logFile%" endlocal
注意:这段代码仅支持Windows系统,若时间差超过24小时,hours会显示累计小时数(如25小时),如需拆分天数需额外处理,整体逻辑繁琐且易出错,不建议使用。
内容的提问来源于stack exchange,提问作者Bawzz
相关产品推荐
相关产品推荐

