Reputation: 26812
Using import datetime
in python, is it possible to take a formatted time/date string such as:
2012-06-21 20:36:11
And convert it into an object that I can then use to produce a newly formatted string such as:
21st June 2012 20:36
Upvotes: 1
Views: 974
Reputation: 56694
import time
s = '2012-06-21 20:36:11'
t = time.strptime(s, '%Y-%m-%d %H:%M:%S')
print time.strftime('%d %B %Y %H:%M', t)
returns
21 June 2012 20:36
If you really want the 'st',
def nth(n):
return str(n) + nth.ext[int(n)%10]
nth.ext = ['th', 'st', 'nd', 'rd'] + ['th']*6
print nth(t.tm_mday) + time.strftime(' %B %Y %H:%M', t)
gets you
21st June 2012 20:36
Upvotes: 6
Reputation: 375942
You want datetime.strptime
, it parses text into datetimes:
>>> d = "2012-06-21 20:36:11"
>>> datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S")
datetime.datetime(2012, 6, 21, 20, 36, 11)
Formatting the date in the way you want is almost doable:
>>> datetime.datetime.strftime(t, "%d %B %Y %H:%m")
'21 June 2012 20:06'
Upvotes: 1