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

如何将Python time.asctime()格式时间转换为Swift Date?

解决Swift DateFormatter解析Python time.asctime()字符串返回nil的问题

我正在处理Python time.asctime()返回的时间字符串,格式形如Sun Jun 20 23:21:05 1993,日期为个位数时会用空格填充(比如Wed Jun 9 04:26:40 1993)。尝试用Swift的DateFormatter解析这类字符串时,始终返回nil,代码和输出如下:

let dateAsString = measurement[2]
print("Date as string: \(dateAsString)")
let df = DateFormatter()
df.dateFormat = "E MMM dd HH:mm:ss y"  
let date = df.date(from: dateAsString)
print("Date: \(String(describing: date))")

输出:

Date as string: Thu Oct 20 17:53:06 2022
Date: nil
Date as string: Thu Oct 20 17:53:06 2022
Date: nil
Date as string: Thu Oct 20 17:53:16 2022
Date: nil

核心原因与修复方案

解析失败的核心问题是DateFormatter的区域设置不匹配:Python asctime()返回的是英文星期和月份缩写,而默认的DateFormatter会使用系统当前区域(如中文),导致无法识别英文标识。同时,年份格式建议明确使用yyyy匹配四位年份,避免歧义。

修正后的代码:

let dateAsString = measurement[2]
print("Date as string: \(dateAsString)")
let df = DateFormatter()
// 设置固定英文区域,确保稳定解析英文格式时间
df.locale = Locale(identifier: "en_US_POSIX")
// 格式完全匹配asctime输出规则
df.dateFormat = "E MMM dd HH:mm:ss yyyy"
// 若时间是GMT时区(由gmtime()生成),需额外设置时区
// df.timeZone = TimeZone(identifier: "GMT")
let date = df.date(from: dateAsString)
print("Date: \(String(describing: date))")

关键细节说明

  • Locale设置:en_US_POSIX是不受系统语言影响的固定英文区域,能确保无论系统语言是什么,都能正确识别英文的星期、月份缩写。
  • 日期格式:dd可以自动适配空格填充的个位数日期(比如Jun 9中的 9),无需额外处理空格。
  • 时区处理:如果你的时间字符串是由Python gmtime()生成的GMT时区时间,必须添加时区设置,否则解析出的Date会使用系统本地时区,导致时间偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:40:30