在python中将日期从DD/MM/YYYY HH.mm.ss转换为MM-DD-YYYY HH:MM:SS时出错

时间:2021-03-14 18:24:49

标签: python date

我有一个数据集,其中有一列意大利格式的“时间戳”:11/03/2004 00.00.00,我需要将其转换为 2004-03-11 00:00:00。我遵循了这篇旧帖子的指南,但是当我尝试这样做时:

for index, row in dataset.iterrows():
   d = datetime.strptime(row['timestamp'], '%d/%m/%y %H.%M.%S')
   row['timestamp'] = d.strftime('%y-%m-%d %H:%M:%s')

我收到错误:

<块引用>

ValueError: 时间数据 '11/03/2004 00.00.00' 与格式 '%d/%m/%y %H.%M.%S' 不匹配

我该如何解决?格式对我来说似乎是正确的

2 个答案:

答案 0 :(得分:3)

您使用了错误的年份格式,根据 documentation,您应该使用 %Y 而不是 %y%y 表示没有世纪的年份。

答案 1 :(得分:1)

from datetime import datetime
datetime.strptime('11/03/2004 00.00.00', '%d/%m/%Y %H.%M.%S')

参考strftime() and strptime() Format Codes