python - 使用 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]....
解决方案
创建时间时,没有指定日期,因此需要 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])
推荐阅读
- c++ - 段错误:链表节点插入函数 [C++]
- python - Python 3.6 正在打印文字字符 \t 和 \n
- angular - 上下文。$隐式。不是功能打字稿错误
- java - 从jar中获取资源文件
- sql - VB - 如何使用数据网格循环查询并将这些结果返回到网格?
- javascript - 访问 javascript 对象失败
- python - 如何将鼠标移动到屏幕上所有蓝色像素的 xy 平均值
- c# - 为什么编译器会抛出错误 CS0165:使用未分配的局部变量?
- codeigniter-3 - 如何在codeigniter中获取数据作为数组
- authentication - ASP.NET WebApi 总是返回 401 Unauthorized