首页 > 解决方案 > 使用 strftime 和 strptime 转换时间格式

问题描述

我有一个 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]....

标签: pythonstrptimestrftime

解决方案


创建时间时,没有指定日期,因此需要 1900 年 1 月。相反,你可以做

date_time=datetime.strptime(row[0]+" "+row[1], '%m/%d/%Y %H:%M:%S %p')
output.append([date_time])
date_str=date_time.strftime('%m/%d/%Y')
time_str=date_time.strftime('%H:%M:%S %p')
csv_output.writerow([date_str,time_str])

推荐阅读