本文目录导读:

Python 脚本示例
基础转换函数
def convert_time(value, from_unit, to_unit):
"""时间单位转换函数"""
# 定义时间单位与秒的换算关系
units = {
'ms': 0.001, # 毫秒
's': 1, # 秒
'min': 60, # 分钟
'h': 3600, # 小时
'd': 86400, # 天
'w': 604800, # 周
'mon': 2592000, # 月(按30天)
'y': 31536000 # 年(按365天)
}
# 先转换为秒
if from_unit.lower() not in units or to_unit.lower() not in units:
return "不支持的时间单位"
seconds = value * units[from_unit.lower()]
result = seconds / units[to_unit.lower()]
return result
# 使用示例
print(convert_time(3600, 's', 'h')) # 输出: 1.0
print(convert_time(7, 'd', 'w')) # 输出: 1.0
print(convert_time(1000, 'ms', 's')) # 输出: 1.0
交互式时间转换器
def time_converter():
print("=== 时间单位转换器 ===")
print("支持的单位: ms(毫秒), s(秒), min(分钟), h(小时), d(天), w(周)")
try:
value = float(input("请输入数值: "))
from_unit = input("请输入原始单位: ")
to_unit = input("请输入目标单位: ")
result = convert_time(value, from_unit, to_unit)
print(f"{value} {from_unit} = {result:.4f} {to_unit}")
except ValueError:
print("请输入有效的数字!")
except Exception as e:
print(f"转换出错: {e}")
# 运行交互式转换器
time_converter()
Bash/Shell 脚本
#!/bin/bash
# 时间单位转换函数
convert_time() {
local value=$1
local from_unit=$2
local to_unit=$3
# 转换为秒
case $from_unit in
s|second|seconds) seconds=$value ;;
min|minute|minutes) seconds=$((value * 60)) ;;
h|hour|hours) seconds=$((value * 3600)) ;;
d|day|days) seconds=$((value * 86400)) ;;
w|week|weeks) seconds=$((value * 604800)) ;;
*) echo "不支持的原单位: $from_unit"; exit 1 ;;
esac
# 从秒转换到目标单位
case $to_unit in
s|second|seconds) result=$seconds ;;
min|minute|minutes) result=$(echo "scale=4; $seconds / 60" | bc) ;;
h|hour|hours) result=$(echo "scale=4; $seconds / 3600" | bc) ;;
d|day|days) result=$(echo "scale=4; $seconds / 86400" | bc) ;;
w|week|weeks) result=$(echo "scale=4; $seconds / 604800" | bc) ;;
*) echo "不支持的目标单位: $to_unit"; exit 1 ;;
esac
echo "$result"
}
# 使用示例
convert_time 3600 s h # 输出: 1.0000
convert_time 7 d w # 输出: 1.0000
PowerShell 脚本
# 时间单位转换函数
function Convert-TimeUnit {
param(
[double]$Value,
[string]$FromUnit,
[string]$ToUnit
)
# 单位换算关系(转换为秒)
$units = @{
'ms' = 0.001
's' = 1
'min' = 60
'h' = 3600
'd' = 86400
'w' = 604800
}
if (-not ($units.ContainsKey($FromUnit) -and $units.ContainsKey($ToUnit))) {
Write-Host "不支持的时间单位" -ForegroundColor Red
return
}
$seconds = $Value * $units[$FromUnit]
$result = $seconds / $units[$ToUnit]
return $result
}
# 使用示例
Convert-TimeUnit -Value 3600 -FromUnit 's' -ToUnit 'h'
高级功能:智能时间字符串解析
import re
def parse_time_string(time_str):
"""解析时间字符串,支持多种格式"""
patterns = {
'd': r'(\d+)\s*d(ay)?s?',
'h': r'(\d+)\s*h(our)?s?',
'm': r'(\d+)\s*m(in(ute)?s?)?',
's': r'(\d+)\s*s(ec(ond)?s?)?'
}
total_seconds = 0
time_str = time_str.lower()
for unit, pattern in patterns.items():
matches = re.findall(pattern, time_str)
for match in matches:
value = int(match[0])
if unit == 'd':
total_seconds += value * 86400
elif unit == 'h':
total_seconds += value * 3600
elif unit == 'm':
total_seconds += value * 60
elif unit == 's':
total_seconds += value
return total_seconds
def smart_time_converter(time_str, to_unit='s'):
"""智能时间转换"""
seconds = parse_time_string(time_str)
conversions = {
's': lambda x: x,
'min': lambda x: x / 60,
'h': lambda x: x / 3600,
'd': lambda x: x / 86400
}
if to_unit in conversions:
return conversions[to_unit](seconds)
else:
return seconds
# 使用示例
print(smart_time_converter("1h 30min", 'h')) # 输出: 1.5
print(smart_time_converter("2 days 5 hours", 'h')) # 输出: 53
使用建议
-
选择脚本语言:根据您的使用环境选择
- Windows 用 PowerShell 或 Python
- Linux/Mac 用 Bash 或 Python
- 跨平台推荐 Python
-
精度要求:
- 使用
float或decimal处理小数 - 使用
scale=4等控制显示精度
- 使用
-
容错处理:
- 添加输入验证
- 处理非法单位和格式
-
扩展功能:
- 添加更多时间单位(毫秒、微秒等)
- 支持批量转换
- 添加时间加减运算
需要我为您定制特定场景的转换脚本吗?