[英]Python3 - Format Date in List
我目前正在嘗試將日期(“ 2017-01-25T09:00”)轉換為%Y-%m-%d%H:%M
我嘗試使用strptime()但收到TypeError:strptime()參數1必須為str,而不是list
我需要在列表中的每個項目上嘗試一下嗎? 在列表中,日期顯示了更多的感謝。
代碼步驟:
這是我目前正在嘗試的:
for line in body:
#newMessageDate = line.get('messagedate')
if line:
date_formats = ["%Y-%m-%d%T%H:%M"]
for date_fmt in date_formats:
try:
line = datetime.datetime.strptime(line, date_fmt).strftime('%Y-%m-%d %H:%M')
except ValueError:
continue
else:
break
輸出的csv文件的精簡版本如下:
driver,id,startdate,startlocation,finsihlocation,finsihtime
Driver 1,3,2016-09-21T12:02,Dublin,2016-09-21T15:02
Driver 2,4,2016-09-21T12:02,Dublin,2016-09-21T15:02
提前致謝!
似乎您正在使用DictReader
從CSV文件DictReader
。 這意味着該line
是在當前行中保存鍵及其值的字典,如當前注釋行#newMessageDate = line.get('messagedate')
。
在這種情況下,您應該使用line.get('messagedate')
而不是line
本身。
newMessageDate = line.get('messagedate')
newMessageDate = datetime.datetime.strptime(newMessageDate, date_fmt).strftime('%Y-%m-%d %H:%M')
(我跳過了循環和try/except
因為它們沒有改變。)
不幸的是,您沒有說明line
外觀。 從最新評論看,您似乎不是讀CSV而是讀JSON,並且該line
是list
而不是dict
。 在這種情況下,您必須使用相應的索引訪問date元素,例如newMessageDate = line[3]
(假設日期在列表的第四位)。 其余答案仍然成立。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.