问题
I have (in Python 3):
print('event {} happened on these dates: {}'.format(event_name, date_list))
My date_list
is a list of datetime.date
objects. I would like to change the format from:
event A happened on [datetime.date(2011, 5, 31), datetime.date(2011, 6, 15)]
to
event A happened on [2011-05-31, 2011-06-15]
What's the best way to achieve that? I was hoping I could keep using the format()
function, but I don't see how.
回答1:
Printing a list gives the repr
of the items inside the list.
To get the str
representation of the items, you have to explicitly call str
on the items:
In [6]: import datetime as dt
In [7]: date_list = [dt.date(2011, 5, 31), dt.date(2011, 6, 15)]
In [8]: print('[{}]'.format(', '.join(map(str,date_list))))
[2011-05-31, 2011-06-15]
来源:https://stackoverflow.com/questions/9052433/overriding-default-format-when-printing-a-list-of-datetime-objects