views:

533

answers:

2

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)')

gives AttributeError: 'time.struct_time' object has no attribute '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")

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

How am I meant to convert a string into a formated date-string?

+2  A: 

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)

gives 05:09 29 December 2009 (UTC)

Josh
+2  A: 

For datetime objects, strptime is a static method of the datetime class, not a free function in the datetime module:

>>> 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)
sth