In the past, whenever I needed to format a datetime.date string, I would do something like this:
date = datetime.date.today()
#Chinese year, month and day.
u'{}年 {}月 {}日'.format(*str(date).split('-'))
#Output: u'2014年 05月 02日'
It worked but I always had a nagging feeling that it’s not clean or pretty enough. So I finally took a moment to rethink it and remembered that you can also access attributes of an object when formatting:
u'{0.year}年 {0.month}月 {0.day}日'.format(date)
#Output: u'2014年 5月 2日'
(Zero is the index of the argument passed to the format method.)
In this case, the two ways are about the same length but the second one is more readable. These are not exactly the same though. Using split in the first method will give you two-digit strings for month and day (i.e. “05”), whereas accessing the attribute only retrieves a number. To get the two-digit output from attributes, add a bit more formatting code:
u'{0.year}年 {0.month:0>2}月 {0.day:0>2}日'.format(date)
#Output: u'2014年 05月 02日'
“0>2” orders up a 2 character long string with the main value served on the right with a side of zeros (if there’s room).