Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime string format alignment

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
like image 671
Marcel Wilson Avatar asked Jun 28 '13 15:06

Marcel Wilson


1 Answers

The problem here is that datetime objects have a __format__ method which is basically just an alias for datetime.strftime. When you do the formatting, the format function gets passed the string '>25' which, as you've seen, dt.strftime('>25') just returns '>25'.

The workaround here it to specify that the field should be formatted as a string explicitly using !s:

import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0!s:>25} {1!s:>25} " 
out = template.format(*l)
print out

(tested on both python2.6 and 2.7).

like image 132
mgilson Avatar answered Oct 02 '22 23:10

mgilson