overriding default format when printing a list of datetime objects

谁说胖子不能爱 提交于 2020-01-03 04:02:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!