我试图强迫自己养成使用数据类的习惯。我正在读取一个包含数据行的文本文件,其中两列包含日期。当我将文件读入类时,为什么日期没有转换为datetime对象
import datetime
from dataclasses import dataclass
@dataclass
class AC07:
NAME: str
MADE_FROM_DATE: datetime.datetime
MADE_UPTO_DATE: datetime.datetime
counter = 0
deck = []
with open(filename, encoding="latin-1") as file:
for line in file:
args = line.strip().split("|")[1:] # not interested in first column
data = AC07(*args)
deck.append(data)
counter += 1
if counter == 10:
break
print (type(deck[0].MADE_FROM_DATE))
<class 'str'>
# Expected behavior <class datetime.datetime>
现在我更好地理解了@vasco ludovico发布的答案,为了解决我的问题,我使用了下面的代码:
请有人纠正我,如果我错了,但我相信数据类不强制类型。在您的示例中,datetime.datetime(几乎)只是一个注释,除了两个实现细节之外。检查documentation。具体来说,
这两个例外与强制数据类型无关:
相关问题 更多 >
编程相关推荐