【问题标题】:Python: How to convert datetime format? [duplicate]Python:如何转换日期时间格式? [复制]
【发布时间】:2011-09-11 10:42:37
【问题描述】:

可能重复:
How to convert a time to a string

我有a 变量,如下面的代码所示。

a = "2011-06-09"

使用python,如何转换成如下格式?

"Jun 09,2011"

【问题讨论】:

标签: python date


【解决方案1】:
>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

在 2.5 之前的 Python 中,您可以将 datetime.strptime 替换为 time.strptime,如下所示(未经测试):datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

【讨论】:

  • Python 2.4 没有 strptime 它只有 strftime
【解决方案2】:

@Tim 的回答只完成了一半的工作——将其放入 datetime.datetime 对象中。

要将其转换为您需要的字符串格式,请使用datetime.strftime

print(datetime.strftime('%b %d,%Y'))

【讨论】:

  • Python 2.4 没有 strptime 它只有 strftime
猜你喜欢
  • 2018-10-16
  • 2014-01-23
  • 1970-01-01
  • 2017-10-31
  • 2012-03-27
  • 2014-06-10
  • 2013-10-04
  • 2013-08-21
相关资源
最近更新 更多