如何写一个脚本批量转换时间戳

wen 实用脚本 2

本文目录导读:

如何写一个脚本批量转换时间戳

  1. Python脚本(最常用)
  2. Shell脚本(Linux/Mac)
  3. 使用说明
  4. 支持的输入格式
  5. 处理毫秒级时间戳
  6. 批量处理示例文件

Python脚本(最常用)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量时间戳转换脚本
支持:Unix时间戳 ↔ 可读日期时间
"""
import datetime
import sys
import os
def timestamp_to_datetime(timestamp, timezone=8):
    """时间戳转日期时间(默认东八区)"""
    try:
        # 处理毫秒级时间戳
        if timestamp > 1e12:
            timestamp = timestamp / 1000
        dt = datetime.datetime.fromtimestamp(timestamp)
        dt = dt + datetime.timedelta(hours=timezone)
        return dt.strftime('%Y-%m-%d %H:%M:%S')
    except:
        return None
def datetime_to_timestamp(date_str, timezone=8):
    """日期时间转时间戳"""
    try:
        formats = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', 
                  '%Y/%m/%d %H:%M:%S', '%Y%m%d', '%Y%m%d%H%M%S']
        for fmt in formats:
            try:
                dt = datetime.datetime.strptime(date_str, fmt)
                dt = dt - datetime.timedelta(hours=timezone)
                return int(dt.timestamp())
            except:
                continue
        return None
    except:
        return None
def batch_convert(input_file, output_file, mode='t2d', timezone=8):
    """
    批量转换
    mode: 't2d' 时间戳→日期, 'd2t' 日期→时间戳
    """
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    results = []
    errors = []
    for i, line in enumerate(lines, 1):
        content = line.strip()
        if not content:
            continue
        if mode == 't2d':
            try:
                timestamp = float(content)
                result = timestamp_to_datetime(timestamp, timezone)
                if result:
                    results.append(f"{content} -> {result}")
                else:
                    errors.append(f"第{i}行: {content} 转换失败")
            except:
                errors.append(f"第{i}行: {content} 不是有效时间戳")
        else:
            result = datetime_to_timestamp(content, timezone)
            if result:
                results.append(f"{content} -> {result}")
            else:
                errors.append(f"第{i}行: {content} 转换失败")
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write('\n'.join(results))
        if errors:
            f.write('\n\n错误记录:\n' + '\n'.join(errors))
    print(f"转换完成!成功: {len(results)}条, 失败: {len(errors)}条")
    print(f"结果保存至: {output_file}")
def main():
    if len(sys.argv) < 2:
        print("用法:")
        print("  交互模式: python timestamp_converter.py")
        print("  命令行模式: python timestamp_converter.py input.txt output.txt [t2d|d2t] [时区]")
        print()
        print("示例:")
        print("  时间戳转日期: python timestamp_converter.py timestamps.txt dates.txt t2d 8")
        print("  日期转时间戳: python timestamp_converter.py dates.txt timestamps.txt d2t 8")
        sys.exit(1)
    if sys.argv[1] == '-i':
        # 交互模式
        interactive_mode()
    else:
        # 命令行模式
        input_file = sys.argv[1]
        output_file = sys.argv[2] if len(sys.argv) > 2 else 'output.txt'
        mode = sys.argv[3] if len(sys.argv) > 3 else 't2d'
        timezone = int(sys.argv[4]) if len(sys.argv) > 4 else 8
        batch_convert(input_file, output_file, mode, timezone)
def interactive_mode():
    print("=== 批量时间戳转换工具 ===")
    print("1. 时间戳转日期时间")
    print("2. 日期时间转时间戳")
    choice = input("请选择转换方向 (1/2): ")
    mode = 't2d' if choice == '1' else 'd2t'
    input_file = input("输入文件路径: ")
    output_file = input("输出文件路径 (默认: output.txt): ") or 'output.txt'
    timezone = input("时区 (默认东八区8): ") or '8'
    if not os.path.exists(input_file):
        print(f"错误: 文件 {input_file} 不存在!")
        return
    batch_convert(input_file, output_file, mode, int(timezone))
if __name__ == "__main__":
    main()

Shell脚本(Linux/Mac)

#!/bin/bash
# batch_timestamp_converter.sh
# 用于批量转换时间戳
# 时间戳转日期
timestamp_to_date() {
    local timestamp=$1
    if [ ${#timestamp} -gt 10 ]; then
        # 毫秒级时间戳
        timestamp=$((timestamp / 1000))
    fi
    date -d "@$timestamp" "+%Y-%m-%d %H:%M:%S"
}
# 主函数
convert_batch() {
    local input_file=$1
    local output_file=$2
    local mode=$3  # "t2d" 或 "d2t"
    if [ ! -f "$input_file" ]; then
        echo "错误: 输入文件 $input_file 不存在"
        exit 1
    }
    while IFS= read -r line; do
        if [ -z "$line" ]; then
            continue
        fi
        if [ "$mode" = "t2d" ]; then
            result=$(timestamp_to_date "$line")
            echo "$line -> $result" >> "$output_file"
        else
            # 这里需要根据具体格式处理日期转时间戳
            result=$(date -d "$line" +%s)
            echo "$line -> $result" >> "$output_file"
        fi
    done < "$input_file"
    echo "转换完成!结果保存至 $output_file"
}
# 使用示例
# 时间戳转日期
# convert_batch timestamps.txt dates.txt t2d
# 日期转时间戳(需要日期格式正确)
# convert_batch dates.txt timestamps.txt d2t

使用说明

准备输入文件

创建文本文件,每行一个时间戳或日期:

# timestamps.txt
1630000000
1630100000
1630200000
1625097600000
# dates.txt
2021-08-27 10:00:00
2021-08-28 10:00:00
2021-08-29 10:00:00

运行脚本

# 时间戳转日期
python timestamp_converter.py timestamps.txt dates.txt t2d 8
# 日期转时间戳
python timestamp_converter.py dates.txt timestamps.txt d2t 8
# 交互模式
python timestamp_converter.py -i

支持的输入格式

脚本支持多种日期格式自动识别:

  • 2021-08-27 10:00:00
  • 2021-08-27 10:00
  • 2021-08-27
  • 2021/08/27 10:00:00
  • 20210827
  • 20210827100000

处理毫秒级时间戳

脚本自动处理:

  • 10位时间戳(秒级)
  • 13位时间戳(毫秒级)
  • 16位时间戳(微秒级)

批量处理示例文件

# 如果你只有一个Excel文件需要处理
import pandas as pd
def convert_excel_timestamps(input_excel, column_name, output_excel):
    """
    转换Excel中的时间戳列
    """
    df = pd.read_excel(input_excel)
    # 假设时间戳在'timestamp'列
    df[column_name] = pd.to_datetime(df[column_name], unit='s')
    # 如果有毫秒级时间戳
    # df[column_name] = pd.to_datetime(df[column_name], unit='ms')
    df.to_excel(output_excel, index=False)
    print(f"转换完成!保存至 {output_excel}")
# 使用
# convert_excel_timestamps('data.xlsx', 'timestamp', 'result.xlsx')

这些脚本支持批量转换,你只需要准备好包含时间戳或日期的文本文件即可,根据你的具体需求选择合适的脚本。

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