使用strftime和strptime转换时间格式

问题描述 投票:0回答:2

我有一个包含三列的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]....
python strptime strftime
2个回答
0
投票
import datetime
a = '1/3/2018'
b = '1:14:12 AM'
in_time = datetime.datetime.strptime(b, "%I:%M:%S %p").time()
print(in_time)
c = datetime.datetime.combine(datetime.datetime.strptime(a, "%d/%m/%Y"), in_time)
print(c.strftime("%d/%m/%Y %I:%M:%S %p"))

试试这个:

Repl Link


0
投票

在创建时间时,没有指定日期,因此需要1900 jan。相反,你可以做到

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])
© www.soinside.com 2019 - 2024. All rights reserved.