首页 > 解决方案 > 将列表中的所有字符串转换为日期格式

问题描述

需要将“all_dates”中存在的字符串转换为日期格式。我能够将它们全部转换为日期格式并在循环内打印。但无法在循环外打印它们。我可以将“AllDates”作为日期列表而不是字符串列表吗

from datetime import datetime, date
from dateutil.relativedelta import relativedelta

all_dates = ['06/11/2020', '26/10/2018']
AllDates = []
for item in range(len(all_dates)):
    dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').date()
    print(dateinAT)
    AllDates.append(dateinAT)
print(AllDates)

上述代码的输出: 2020-11-06 2018-10-26

[datetime.date(2020, 11, 6), datetime.date(2018, 10, 26)]

所需输出: [2020-11-06, 2018-10-26]

标签: pythondatetimepython-datetime

解决方案


在 OP 澄清他们想要保留对象AllDates列表后回答date。所有其他答案都将其作为字符串列表

首先,重要的是要理解这只是一个表示的东西。当您在循环内打印时,您会以返回它dateinAT的格式获得输出。datetime.date.__str__但是,当您AllDates在循环之外打印列表时,您会以返回date的格式获取每个对象。datetime.date.__repr__

请参阅__str__ 和 __repr__ 之间的区别?有关__str__和的更多信息__repr__

清除后,如果您仍然认为值得[2020-11-06, 2018-10-26]作为 的输出print(AllDates),这可以通过使用list具有自定义实现的子类的类来实现__str__(它将使用每个元素的__str__方法而不是__repr__)。

from collections import UserList

class DatesList(UserList):
    def __str__(self):
        return '[' + ', '.join(str(e) for e in self) + ']'
        # as an exercise, change str(e) to repr(e) and see that you get the default output


all_dates = ['06/11/2020', '26/10/2018']
AllDates = DatesList() # <- note we use our new class instead of list() or []
for item in range(len(all_dates)):
    dateinAT = datetime.strptime(all_dates[item], '%d/%m/%Y').date()
    AllDates.append(dateinAT)

print(AllDates)
print([type(e) for e in AllDates])

这输出

[2020-11-06, 2018-10-26]
[<class 'datetime.date'>, <class 'datetime.date'>]

保留AllDates一个date对象列表。


推荐阅读