Reputation:
I have a date timestamp like "2013-12-20 23:40:33". Now, my requirement is to re-format this date in reverse order like :
<seconds><minutes><hr><day><month><year>
in python. Please suggest
Upvotes: 0
Views: 9039
Reputation: 11
d = "2013-12-20 23:40:33"
date = d[17]+d[18]+":"+d[14]+d[15]+":"+d[11]+d[12]+" "+d[8]+d[9]+"-"+d[5]+d[6]+"-"+d[0]+d[1]+d[2]+d[3]
print(d)
print(date)
Upvotes: 0
Reputation: 414585
If you don't need to validate the time string:
>>> import re
>>> '<%s>' % '><'.join(re.findall(r'\d+', "2013-12-20 23:40:33")[::-1])
'<33><40><23><20><12><2013>'
It is 6 times faster than the corresponding datetime
solution:
>>> from datetime import datetime
>>> datetime.strptime("2013-12-20 23:40:33", '%Y-%m-%d %H:%M:%S').strftime('<%S><%M><%H><%d><%m><%Y>')
'<33><40><23><20><12><2013>'
Or 5 times faster than time
solution:
>>> import time
>>> time.strftime('<%S><%M><%H><%d><%m><%Y>', time.strptime("2013-12-20 23:40:33", '%Y-%m-%d %H:%M:%S'))
'<33><40><23><20><12><2013>'
Upvotes: 2
Reputation: 474001
Load the string into a datetime
object with strptime
and format to string with strftime
:
>>> from datetime import datetime
>>> datetime.strptime(s, '%Y-%m-%d %H:%M:%S').strftime('%S:%M:%H %d-%m-%Y')
'33:40:23 20-12-2013'
Upvotes: 5
Reputation: 133634
>>> import datetime
>>> datetime.datetime.strptime('2013-12-20 23:40:33', '%Y-%m-%d %H:%M:%S').strftime('%S:%M:%H %d-%m-%Y')
'33:40:23 20-12-2013'
Upvotes: 3