python - 数字到月年?

标签 python python-3.x date

有没有简单的方法可以将代表月份和年份的数字转换为文本?

例如:

1208
109
209
309
409

会是:

December 2008
January 2009
February 2009
March 2009
April 2009

目前我能想到的唯一方法是通过一系列 if/else 语句。

最佳答案

当然,我们的想法是:

  • 将数字转换为字符串
  • 使用.strptime()将字符串加载到日期时间对象中
  • 使用.strftime()将日期时间转储为所需格式的字符串(在您的情况下为 %B %Y)

演示:

In [1]: l = [1208, 109, 209, 309, 409]

In [2]: [datetime.strptime(str(item), "%m%y").strftime("%B %Y") for item in l]
Out[2]: ['December 2008', 'January 2009', 'February 2009', 'March 2009', 'April 2009']

关于python - 数字到月年?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42006224/

相关文章:

python - 如何在 python 中使用 selenium 中预定义的 chrome 配置文件?

javascript - 在 Javascript/NodeJS 中返回调整时区的当前日期,然后在早上 6 点找到相当于用户时间的 UTC

java - 我的无效和有效日期代码不显示

python - Pyramid 调试工具栏导致内存 "leak"

python - Pandas 的差异但用户定义的函数

python - 带有列表的 Pandas 数据框中的唯一项目

Python 3.x 的字典 View 对象和 matplotlib

通过函数传递数组时python列表索引超出范围

python - 如何从第一个 python 脚本启动几个 python 脚本,然后立即终止它们?

python - 检查字符串是否有日期,任何格式