我有一个dict,其中包含一系列欧洲格式的日期(%d/%m/%Y)
。
我正在尝试重新格式化日期,以便它们采用美国格式(%m/%d/%Y)
。
每当我运行它时,都会发现以下错误:
ValueError: time data '2' does not match format '%m/%d/%Y'
任何人都知道我需要纠正什么? 谢谢你的帮助!
from datetime import datetime
import time
from time import mktime
Transaction_Date=[
"23/08/2017",
"23/08/2017",
"21/08/2017",
"01/10/2017",
"19/08/2017",
"19/08/2017",
"18/08/2017",
"03/09/2017",
"27/09/2017",
"26/08/2017",
"03/10/2017",
"27/09/2017",
"27/03/2017",
"02/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017",
"20/08/2017"]
for row in Transaction_Date:
Transaction_Date = row[0]
Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
print(Transaction_Date)
给出以下错误:
ValueError: time data '2' does not match format '%m/%d/%Y'
据我所知,日期格式是正确的,为什么系统说不同?
答案 0 :(得分:0)
您的代码有2个错误: -
对收集和结果使用相同的名称(Transition_Date
),
您使用row[0]
代替row
from datetime import datetime
import time
from time import mktime
Transaction_Date_Collection = [ "23/08/2017", "23/08/2017", "21/08/2017", "01/10/2017", "19/08/2017", "19/08/2017", "18/08/2017", "03/09/2017", "27/09/2017", "26/08/2017", "03/10/2017", "27/09/2017", "27/03/2017", "02/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017"]
for Transaction_Date in Transaction_Date_Collection:
Transaction_Date = datetime.strptime(Transaction_Date,'%d/%m/%Y').strftime('%m/%d/%Y')
print(Transaction_Date)
答案 1 :(得分:0)
您只需在循环中使用row
,如下所示:
from datetime import datetime
Transaction_Dates = [
"23/08/2017", "23/08/2017", "21/08/2017", "01/10/2017",
"19/08/2017", "19/08/2017", "18/08/2017", "03/09/2017",
"27/09/2017", "26/08/2017", "03/10/2017", "27/09/2017",
"27/03/2017", "02/08/2017", "20/08/2017", "20/08/2017",
"20/08/2017", "20/08/2017", "20/08/2017", "20/08/2017"]
for row in Transaction_Dates:
print(datetime.strptime(row, '%d/%m/%Y').strftime('%m/%d/%Y'))
显示:
08/23/2017
08/23/2017
08/21/2017
10/01/2017
08/19/2017
08/19/2017
08/18/2017
09/03/2017
09/27/2017
08/26/2017
10/03/2017
09/27/2017
03/27/2017
08/02/2017
08/20/2017
08/20/2017
08/20/2017
08/20/2017
08/20/2017
08/20/2017