如何在 Python3 的日期列表中查找所有日期

How to find all dates within a list of dates with Python3

我有这样的 UTC 日期列表:

['2018-07-29T15:58:22.111904Z', '2018-07-29T15:59:22.033263Z', '2018-07-29T16:01:22.103157Z', '2018-07-30T11:41:22.032661Z', '2018-07-30T11:42:22.042215Z', '2018-07-31T12:31:21.062671Z']

这不是完整列表。我需要的是获取整个列表中找到的所有日期。

因此对于此列表:

['2018-07-29', '2018-07-30', '2018-07-31']

会被退回。

如何使用 Python3 完成此操作?

您可以将集合理解与字符串切片结合使用:

L = ['2018-07-29T15:58:22.111904Z', '2018-07-29T15:59:22.033263Z',
     '2018-07-29T16:01:22.103157Z', '2018-07-30T11:41:22.032661Z',
     '2018-07-30T11:42:22.042215Z', '2018-07-31T12:31:21.062671Z']

res = {i[:10] for i in L}

结果:

print(res)

{'2018-07-30', '2018-07-31', '2018-07-29'}

如果您需要列表并且不关心顺序,请使用 list(res)

如果您需要 排序的 列表,请使用 sorted(res)


如果您希望使用 datetime 对象(强烈推荐),您应该转换为 datetime 并使用 date 方法。这是第 3 方 dateutil 模块的一种方式:

from dateutil import parser

res = {parser.parse(i).date() for i in L}

print(res)

{datetime.date(2018, 7, 29),
 datetime.date(2018, 7, 30),
 datetime.date(2018, 7, 31)}

可以像以前一样进行列表转换和排序。