【问题标题】:Converting time format with strftime and strptime使用 strftime 和 strptime 转换时间格式
【发布时间】: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_strtime_str。如果您将这些附加到输出,打印语句将如预期的那样。
  • 将此行 output.append([date, time]) 更改为 output.append([date_str, time_str]) 并将其向下移动两行。查看您可能想要的预期结果output.append(date_str + ' ' + time_str)

标签: python strptime strftime


【解决方案1】:
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

【讨论】:

  • 你好,为什么它显示类型对象'datetime.datetime'没有属性'datetime'...
  • 您是否正在导入datetime 并像datetime.strptime/datetime.strftime 一样使用它?
【解决方案2】:

创建时间时,没有指定日期,因此需要 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])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2022-11-10
    • 2016-07-12
    • 1970-01-01
    • 2017-02-14
    • 2016-10-20
    相关资源
    最近更新 更多