【发布时间】:2019-03-28 16:32:51
【问题描述】:
我有一个包含三列的 csv 文件。首先是1/3/2018 格式的日期。其次是时间10:00:00 AM。三是温度。现在我想使用strftime()将datetime对象转换为"YYYY/MM/DD HH:MM:SS AM"格式,并存储温度超过80的时间列表。
import csv
from datetime import datetime
with open("temp.csv") as csvfile, open('output.csv','w') as output_file: #types of file opened "wb": binary file
csv_reader = csv.reader(csvfile, delimiter=",")
csv_output = csv.writer(output_file)
next(csv_reader, None) #skip header
rows = [row for row in csv_reader if row[2] >= '80.0'] #if condition
output = []
for row in rows:
date = datetime.strptime(row[0], '%m/%d/%Y') # strp is a function under datetime. convert a string to a datetime object
time = datetime.strptime(row[1], '%H:%M:%S %p')
output.append([date, time])
date_str = date.strftime('%m/%d/%Y') #strftime: convert datetime object into a string
time_str = time.strftime('%H:%M:%S %p')
csv_output.writerow([date_str,time_str])
print(output)
目前的结果是:
[[datetime.datetime(2018, 1, 2, 0, 0), datetime.datetime(1900, 1, 1, 5, 0)], [datetime.datetime(2018, 1, 2, 0, 0)...
我希望结果是:
[1/2/2018 10:00:00 ], [1/2/2018 11:00:00]....
【问题讨论】:
-
目前您将原始
datetime对象附加到output而不是date_str和time_str。如果您将这些附加到输出,打印语句将如预期的那样。 -
将此行
output.append([date, time])更改为output.append([date_str, time_str])并将其向下移动两行。查看您可能想要的预期结果output.append(date_str + ' ' + time_str)