__列表(或元组)的str____________________)显示日期时间,因此无法读取

2024-06-01 02:00:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还很陌生。 我正在开发一个使用Datetime对象列表的应用程序(来自Datetime模块)

我想调试我的应用程序,所以我打印(或记录)这些列表,但它会返回以下内容:

>>> print(list_with_datetimes_and_timedeltas) # print calls __str__ (by default), but list's __str__ calls the item's __repr__
[(None, 1, datetime.datetime(2020, 11, 1, 18, 44, 12, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Paris, Madrid'))), (datetime.timedelta(seconds=110, microseconds=7), 1, datetime.datetime(2020, 11, 1, 18, 46, 2, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Paris, Madrid'))), (datetime.timedelta(seconds=103, microseconds=5), 1, datetime.datetime(2020, 11, 1, 1) .....

这是不可读的,这是因为列表。str()返回每个项目的repr(据我所知)

Datetimes和TimeDelta的str没有问题:

>>> print(my_list_with_datetimes_and_timedeltas[0][2])
2020-11-01 18:44:12+01:00 #which is what I would like in the list for the datetimes
>>> print(my_list_with_datetimes_and_timedeltas[1][0])
0:01:50.000007 #which is what I would like in the list for the timedeltas

我考虑过多种解决方案,但我真的不知道如何选择,以及它们是否可行:

  • 更改内置列表行为,使其返回项的__str__表示,而不是它们的__repr__,因为我不明白如果我在列表上调用__str__,为什么它会返回__repr__个对象(但这似乎不是一个好主意,我甚至不知道是否可行)
  • 在模块Datetime中更改Datetime对象的buildtins__repr__(看起来也不是个好主意)
  • as Dan said here,我可以print([str(item) for item in mylist]),但每次打印列表时,我都必须对每个日志的每一行执行此操作(在这里甚至不起作用,因为它是元组列表)
  • 我还使用一个记录器(来自日志记录)。如果我在那里换些东西可以吗

你有什么解决办法吗?(当我们在列表上调用str时,Python选择该选项的原因是什么?它显示了项的repr


Tags: andthe对象列表datetimewithlisttimedelta