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

如何用Python从字典的时间戳中提取月份并转换为指定格式

问题描述

给定如下数据字典:

data = {
  "36": "Tue, 31 Jan 2023 16:00:00 GMT", 
  "240": "Wed, 30 Nov 2022 16:00:00 GMT", 
  "284": "Sat, 31 Dec 2022 16:00:00 GMT", 
  "1012": "Mon, 31 Oct 2022 16:00:00 GMT", 
  "2170": "Wed, 31 Aug 2022 16:00:00 GMT", 
  "7512": "Fri, 30 Sep 2022 16:00:00 GMT"
}

尝试了以下代码:

for m in dict.values:
    m = m.dt.month

需要得到指定输出:

{"Jan 2023": "36", "Nov 2022": "240", "Dec 2022": "284", "Oct 2022": "1012", "Aug 2022": "2170", "Sep 2022": "7512"}
正确Python实现方法

你之前的代码存在两个问题:

  • dict.values 缺少括号,正确写法是 dict.values() 来获取值的迭代器
  • 原字典的值是普通字符串,没有 dt.month 属性(这是pandas时间序列对象的专属方法)

可以用Python标准库的datetime模块解析时间字符串,重新构建目标字典:

from datetime import datetime

data = {
    "36": "Tue, 31 Jan 2023 16:00:00 GMT",
    "240": "Wed, 30 Nov 2022 16:00:00 GMT",
    "284": "Sat, 31 Dec 2022 16:00:00 GMT",
    "1012": "Mon, 31 Oct 2022 16:00:00 GMT",
    "2170": "Wed, 31 Aug 2022 16:00:00 GMT",
    "7512": "Fri, 30 Sep 2022 16:00:00 GMT"
}

result = {}
for key, date_str in data.items():
    # 解析GMT格式的时间字符串为datetime对象
    date_obj = datetime.strptime(date_str, "%a, %d %b %Y %H:%M:%S %Z")
    # 格式化为"月 年"的形式作为新字典的键
    new_key = date_obj.strftime("%b %Y")
    result[new_key] = key

print(result)

运行后得到的输出完全符合需求:

{'Jan 2023': '36', 'Nov 2022': '240', 'Dec 2022': '284', 'Oct 2022': '1012', 'Aug 2022': '2170', 'Sep 2022': '7512'}

代码说明

  1. datetime.strptime():按照指定格式将字符串解析为datetime对象,其中%a对应星期缩写、%d对应日期、%b对应月份缩写、%Y对应4位年份、%Z对应时区。
  2. date_obj.strftime("%b %Y"):将datetime对象格式化为「月份缩写+年份」的字符串,作为新字典的键。
  3. 遍历原字典的键值对,反转存储到新字典中完成转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:40:45