python - 将列表中的所有字符串转换为日期格式
问题描述
需要将“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]
解决方案
在 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
对象列表。
推荐阅读
- java - 如何使用控制器类切换场景,以 ActionEvent 作为参数?
- xml - 如何使用 LET 和 WHERE 获取元素的名称?
- bash - 检查脚本中的目录是否存在会产生错误“不存在”
- terraform - 当 azure 策略要求所有子网上的 NSG 时,如何处理 Terraform 销毁操作?
- python - 如何在条形图上隔开 x 刻度并缩放 y 轴
- javascript - 在 es6、javascript 中使用 rest 参数 concat
- mysql - 在 laravel 播种机类中存储真实数据可以吗?
- html - 使用 url 作为 ar.js 和 A-frame 的源设置多个 3D 模型时出现问题
- docker - Hyperledger Fabric - 无法实例化 - 元数据中缺少合约 org.hyperledger.fabric
- css - 如何为链接应用边框?