【问题标题】:Convert list of datetime() and other types into string [duplicate]将 datetime() 和其他类型的列表转换为字符串 [重复]
【发布时间】:2022-02-15 04:20:03
【问题描述】:

在python中,我们如何转换这个列表,以便将日期时间转换为字符串:

list = [
    datetime.datetime(2020, 12, 31, 0, 0),
    "some string",
    datetime.datetime(2014, 11, 20, 1, 0),
    "another string"]

想要的输出:

["2020-12-31 00:00", "some string", "2014-11-20: 01:00", "another string"]

【问题讨论】:

  • 请编辑您的问题,让问题变得更加确定。解释你想要的结果。到目前为止你尝试了什么?你遇到了什么问题?
  • 欢迎来到 Stack Overflow!请使用tour 并阅读How to Ask。我在现有问题下关闭了您的问题,该问题涵盖如何将任何内容转换为字符串,但如果这不能回答您的问题,例如,如果您不知道如何遍历列表,您可以edit 澄清,请提及您已经尝试过的内容。
  • 2014-11-20: 好像多了一个冒号

标签: python list datetime


【解决方案1】:

首先,小心使用list作为变量名,它会将shadow作为数据类型的内置名称。

要将列表转换为所有字符串,请尝试:

x = [str(item) for item in x]

其中x 是列表的变量名。

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多