You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将CSV中特定日期时间字符串转为YYYY-MM-DD HH:MM格式

解决CSV日期格式转换问题

首先看报错信息里的日期字符串是Sunday August 7,2022 6:26 PM GMT,和你定义的格式串%A %B %d, %Y %I:%M %p %Z不匹配的核心原因是:逗号和年份之间没有空格,但格式串里写的是, %Y(逗号后带空格)。除此之外,Python的datetime.strptime对%Z的支持有限,部分环境下GMT可能无法被正确解析,需要额外处理。

修正后的转换函数

下面是适配两种情况(逗号后有/无空格)且处理时区、输出目标格式的代码:

from datetime import datetime
import re

def convert_to_timestamp(date_string):
    # 统一处理逗号后的空格问题:把逗号后可能的空格去掉或补上,统一成带空格的格式
    normalized_date = re.sub(r',(\d{4})', r', \1', date_string)
    # 定义匹配格式
    date_format = "%A %B %d, %Y %I:%M %p %Z"
    try:
        # 解析日期,GMT为UTC+0,不影响日期时间转换
        dt = datetime.strptime(normalized_date, date_format)
        # 输出目标格式 YYYY-MM-DD HH:MM
        return dt.strftime("%Y-%m-%d %H:%M")
    except ValueError:
        # 如果时区解析失败,尝试去掉时区部分解析
        normalized_date_no_tz = re.sub(r' GMT$', '', normalized_date)
        date_format_no_tz = "%A %B %d, %Y %I:%M %p"
        dt = datetime.strptime(normalized_date_no_tz, date_format_no_tz)
        return dt.strftime("%Y-%m-%d %H:%M")

批量处理CSV的示例(用csv模块)

如果你需要批量处理CSV文件,可以用Python内置的csv模块读取并转换:

import csv

input_csv = "input.csv"
output_csv = "output.csv"

with open(input_csv, 'r', encoding='utf-8') as infile, open(output_csv, 'w', newline='', encoding='utf-8') as outfile:
    reader = csv.DictReader(infile)
    fieldnames = reader.fieldnames
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    writer.writeheader()
    
    for row in reader:
        # 假设日期字段名为'date',请根据实际字段名修改
        row['date'] = convert_to_timestamp(row['date'])
        writer.writerow(row)

关键说明

  • 正则替换re.sub(r',(\d{4})', r', \1', date_string)是为了兼容两种格式:逗号后有空格和无空格的情况,避免因为格式不一致导致解析失败。
  • 时区处理做了容错:如果%Z解析失败,就去掉GMT再解析,因为GMT对应的是UTC时间,不影响最终的日期时间转换结果(若需处理时区偏移,可使用zoneinfo或pytz模块扩展)。
  • 最终用strftime("%Y-%m-%d %H:%M")把datetime对象转换成你需要的字符串格式。

内容的提问来源于stack exchange,提问作者WR7500

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 04:28:32