使用Python将字符串转换为格式化的日期时间字符串

匿名 (未验证) 提交于 2019-12-02 22:51:30

我正在尝试将字符串“20091229050936”转换为“2009年12月29日(UTC)”

>>>import time >>>s = time.strptime("20091229050936", "%Y%m%d%H%M%S") >>>print s.strftime('%H:%M %d %B %Y (UTC)')

AttributeError: 'time.struct_time' object has no attribute 'strftime'

显然,我犯了一个错误:时间错了,它是一个日期时间对象!它有一个日期时间组件!

>>>import datetime >>>s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")

AttributeError: 'module' object has no attribute 'strptime'

我是怎么意思将字符串转换为格式化的日期字符串?

解决方案


time.strptime返回time_struct; time.strftime接受a time_struct作为可选参数:

>>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S") >>>print time.strftime('%H:%M %d %B %Y (UTC)', s)

05:09 29 December 2009 (UTC)


本文首发于Python黑洞网,博客园同步跟新

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!