将列表中的所有字符串转换为日期格式
Convert all the strings in a list to date format
需要将“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]
print()
调用了datetime.date对象的__str__
方法。
解决问题的快速但不那么复杂的方法是:
AllDates.append(dateinAT.__str__())
更好的版本是使用 strftime
方法
AllDates.append(dateinAT.strftime("%Y-%m-%d"))
您将值存储为 datetime
值。因此,您需要使用 strftime
.
将其转换为 str
因此,将此行更改为
dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').date()
这个
dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').strftime('%Y-%m-%d')
使用列表理解:
>>> from datetime import datetime
>>> all_dates = ['06/11/2020', '26/10/2018']
>>> AllDates = [
datetime.strptime(item, '%d/%m/%Y').date().strftime('%Y-%m-%d') for item in all_dates]
['2020-11-06', '2018-10-26']
在 OP 澄清他们想要保留 AllDates
一个 date
对象的列表后回答。所有其他答案都将其作为字符串列表
首先,重要的是要了解这只是一种表现形式。当你在循环中打印 dateinAT
时,你会得到 datetime.date.__str__
returns 格式的输出。但是,当您在循环外打印 AllDates
列表时,您会得到每个 date
对象,其格式为 datetime.date.__repr__
returns.
有关 __str__
和 __repr__
的更多信息,请参阅 Difference between __str__ and __repr__?。
清除之后,如果你仍然认为 [2020-11-06, 2018-10-26]
作为 print(AllDates)
的输出是值得的,这可以通过使用 class 来实现,即 subclasses 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
个对象的列表。
需要将“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]
print()
调用了datetime.date对象的__str__
方法。
解决问题的快速但不那么复杂的方法是:
AllDates.append(dateinAT.__str__())
更好的版本是使用 strftime
方法
AllDates.append(dateinAT.strftime("%Y-%m-%d"))
您将值存储为 datetime
值。因此,您需要使用 strftime
.
str
因此,将此行更改为
dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').date()
这个
dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').strftime('%Y-%m-%d')
使用列表理解:
>>> from datetime import datetime
>>> all_dates = ['06/11/2020', '26/10/2018']
>>> AllDates = [
datetime.strptime(item, '%d/%m/%Y').date().strftime('%Y-%m-%d') for item in all_dates]
['2020-11-06', '2018-10-26']
在 OP 澄清他们想要保留 AllDates
一个 date
对象的列表后回答。所有其他答案都将其作为字符串列表
首先,重要的是要了解这只是一种表现形式。当你在循环中打印 dateinAT
时,你会得到 datetime.date.__str__
returns 格式的输出。但是,当您在循环外打印 AllDates
列表时,您会得到每个 date
对象,其格式为 datetime.date.__repr__
returns.
有关 __str__
和 __repr__
的更多信息,请参阅 Difference between __str__ and __repr__?。
清除之后,如果你仍然认为 [2020-11-06, 2018-10-26]
作为 print(AllDates)
的输出是值得的,这可以通过使用 class 来实现,即 subclasses 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
个对象的列表。