我正在尝试将字符串“20091229050936”转换为“05:09 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' 对象没有属性 'strftime'
显然,我犯了一个错误:时间是错误的,它是一个日期时间对象!它有一个日期和一个时间组件!
>>>import datetime
>>>s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
给予
AttributeError: 'module' 对象没有属性 'strptime'
如何将字符串转换为格式化的日期字符串?
最佳答案
对于 datetime
对象,strptime
是 static method datetime
类的,不是 datetime
模块中的自由函数:
>>> import datetime
>>> s = datetime.datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
>>> print s.strftime('%H:%M %d %B %Y (UTC)')
05:09 29 December 2009 (UTC)
关于python - 使用 Python 将字符串转换为格式化的日期时间字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2316987/