如何用脚本转换日期格式

wen 实用脚本 2

本文目录导读:

如何用脚本转换日期格式

  1. Python(最常用)
  2. JavaScript/Node.js
  3. Shell/Bash(使用date命令)
  4. 常用转换格式对照表
  5. 批量处理文件的Python脚本
  6. 使用建议:

我来介绍几种常见的方法来转换日期格式,使用不同的脚本语言:

Python(最常用)

from datetime import datetime
# 方法1:字符串转字符串
def convert_date(date_str, from_format, to_format):
    """转换日期格式
    convert_date("2024-01-15", "%Y-%m-%d", "%d/%m/%Y") → "15/01/2024"
    """
    dt = datetime.strptime(date_str, from_format)
    return dt.strftime(to_format)
# 示例
print(convert_date("2024-01-15", "%Y-%m-%d", "%d/%m/%Y"))  # 15/01/2024
print(convert_date("01/15/2024", "%m/%d/%Y", "%Y年%m月%d日"))  # 2024年01月15日
# 方法2:批量处理文件
def bulk_convert(input_file, output_file, from_format, to_format):
    with open(input_file, 'r') as f_in, open(output_file, 'w') as f_out:
        for line in f_in:
            line = line.strip()
            try:
                converted = convert_date(line, from_format, to_format)
                f_out.write(converted + '\n')
            except:
                f_out.write(line + '\n')  # 保留无法转换的行

JavaScript/Node.js

// 使用JavaScript
function convertDate(dateStr, fromFormat, toFormat) {
    const map = {
        'YYYY': 'year', 'MM': 'month', 'DD': 'day',
        'HH': 'hours', 'mm': 'minutes', 'ss': 'seconds'
    };
    // 解析日期字符串
    let date = {};
    for (let key in map) {
        let regex = new RegExp(key);
        let match = dateStr.match(regex);
        if (match) {
            date[map[key]] = parseInt(match[0]);
        }
    }
    // 创建Date对象(注意:月份从0开始)
    const d = new Date(date.year || 0, 
                       (date.month || 1) - 1, 
                       date.day || 1, 
                       date.hours || 0, 
                       date.minutes || 0, 
                       date.seconds || 0);
    // 格式化输出
    const pad = (num) => String(num).padStart(2, '0');
    return toFormat
        .replace('YYYY', d.getFullYear())
        .replace('MM', pad(d.getMonth() + 1))
        .replace('DD', pad(d.getDate()))
        .replace('HH', pad(d.getHours()))
        .replace('mm', pad(d.getMinutes()))
        .replace('ss', pad(d.getSeconds()));
}
// 或使用更简单的方案(Node.js环境)
const { format, parse } = require('date-fns');
function convertDateModern(dateStr, fromFormat, toFormat) {
    const date = parse(dateStr, fromFormat, new Date());
    return format(date, toFormat);
}
// 示例
console.log(convertDate("2024-01-15", "YYYY-MM-DD", "DD/MM/YYYY")); // 15/01/2024

Shell/Bash(使用date命令)

#!/bin/bash
# 简单的日期转换函数
convert_date() {
    local input_date="$1"
    local from_format="$2"
    local to_format="$3"
    # 转换格式标识符
    case "$from_format" in
        "YYYY-MM-DD") from_str="%Y-%m-%d" ;;
        "MM/DD/YYYY") from_str="%m/%d/%Y" ;;
        "DD/MM/YYYY") from_str="%d/%m/%Y" ;;
        *) from_str="$from_format" ;;
    esac
    case "$to_format" in
        "YYYY-MM-DD") to_str="%Y-%m-%d" ;;
        "MM/DD/YYYY") to_str="%m/%d/%Y" ;;
        "DD/MM/YYYY") to_str="%d/%m/%Y" ;;
        *) to_str="$to_format" ;;
    esac
    date -j -f "$from_str" "$input_date" +"$to_str" 2>/dev/null || \
    date -d "$input_date" +"$to_str"
}
# 使用示例
echo "转换结果: $(convert_date "2024-01-15" "YYYY-MM-DD" "DD/MM/YYYY")"

常用转换格式对照表

# Python格式说明(以strftime/strptime为例)
"""
%Y  - 4位年份 (2024)
%y  - 2位年份 (24)
%m  - 月份 (01-12)
%d  - 日期 (01-31)
%H  - 24小时制 (00-23)
%I  - 12小时制 (01-12)
%M  - 分钟 (00-59)
%S  - 秒 (00-59)
%p  - AM/PM
%b  - 月份缩写 (Jan, Feb...)
%B  - 月份全称 (January...)
%a  - 星期缩写 (Mon, Tue...)
%A  - 星期全称 (Monday...)
%j  - 年中的第几天 (001-366)
"""

批量处理文件的Python脚本

#!/usr/bin/env python3
import re
import sys
from datetime import datetime
def process_csv_file(input_file, output_file, column_index=0):
    """处理CSV文件中的日期列"""
    with open(input_file, 'r', encoding='utf-8') as f_in, \
         open(output_file, 'w', encoding='utf-8') as f_out:
        header = f_in.readline()
        f_out.write(header)
        for line in f_in:
            columns = line.strip().split(',')
            try:
                # 假设日期格式为 YYYY-MM-DD
                dt = datetime.strptime(columns[column_index], '%Y-%m-%d')
                # 转换为 MM/DD/YYYY 格式
                columns[column_index] = dt.strftime('%m/%d/%Y')
            except (ValueError, IndexError):
                pass  # 跳过无法处理的行
            f_out.write(','.join(columns) + '\n')
# 命令行用法
if __name__ == '__main__':
    if len(sys.argv) == 4:
        process_csv_file(sys.argv[1], sys.argv[2], int(sys.argv[3]))
    else:
        print("用法: python convert_dates.py 输入文件 输出文件 列索引")

使用建议:

  1. 小批量数据:使用Python脚本最方便
  2. 单次转换:使用date命令最快(Linux/Mac)
  3. Web应用:使用JavaScript(需用date-fns或moment.js)
  4. Excel文件:使用Python的openpyxlpandas

需要针对特定场景(如JSON、XML、数据库导入等)进一步定制吗?

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