打印日期时间对象列表时覆盖默认格式 [英] overriding default format when printing a list of datetime objects

查看:278
本文介绍了打印日期时间对象列表时覆盖默认格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有(在Python 3中):

$ p $ print('event {}发生在这些日期:{}'。格式(event_name,date_list))

我的 date_list datetime.date 对象的列表。我想改变格式:
$ b


事件发生在[datetime.date(2011,5,31),datetime.date (2011,
6,15)]



事件发生在[2011-05-31,2011-06-15]


什么是最好的方法来实现呢?我希望我可以继续使用 format()函数,但是我不知道如何。

解决方案

打印列表给出列表中的项目的 repr
为了得到这些项的 str 表示,你必须显式地调用 str / p>

 在[6]中:import datetime as dt 

在[7]中:date_list = [dt。 date(2011,5,31),dt.date(2011,6,15)]

在[8]中:print('[{}]'。format(','.join map(str,date_list))))
[2011-05-31,2011-06-15]


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.

解决方案

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]

这篇关于打印日期时间对象列表时覆盖默认格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆