In Python 2.7 I want to print datetime objects using string formatted template. For some reason using left/right justify doesn't print the string correctly.
import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0:>25} {1:>25}" # right justify
print template.format(*l) #print items in the list using template
This will result:
>25 >25
Instead of
2013-06-26 09:00:00 2013-06-26 09:00:00
Is there some trick to making datetime objects print using string format templates?
It seems to work when I force the datetime object into str()
print template.format(str(l[0]), str(l[1]))
but I'd rather not have to do that since I'm trying to print a list of values, some of which are not strings. The whole point of making a string template is to print the items in the list.
Am I missing something about string formatting or does this seem like a python bug to anyone?
SOLUTION
@mgilson pointed out the solution which I missed in the documentation. link
Two conversion flags are currently supported: '!s' which calls str() on the value, and '!r' which calls repr().
Some examples:
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first