使用 Python 将字符串转换为格式化的日期时间字符串 [英] Converting a string to a formatted date-time string using Python
本文介绍了使用 Python 将字符串转换为格式化的日期时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将字符串20091229050936"转换为2009 年 12 月 29 日 05:09 (UTC)"
I'm trying to convert a string "20091229050936" into "05:09 29 December 2009 (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'
显然,我犯了一个错误:时间不对,它是一个日期时间对象!它有一个日期和一个时间组件!
Clearly, I've made a mistake: time is wrong, it's a datetime object! It's got a date and a time component!
>>>import datetime
>>>s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
给AttributeError: 'module' 对象没有属性 'strptime'
我打算如何将字符串转换为格式化的日期字符串?
How am I meant to convert a string into a formatted date-string?
推荐答案
time.strptime
返回一个 time_struct
;time.strftime
接受一个 time_struct
作为可选参数:
time.strptime
returns a time_struct
; time.strftime
accepts a time_struct
as an optional parameter:
>>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S")
>>>print time.strftime('%H:%M %d %B %Y (UTC)', s)
给05:09 2009 年 12 月 29 日(UTC)
这篇关于使用 Python 将字符串转换为格式化的日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文