【问题标题】:How to read date and time from csv in python? [duplicate]如何从python中的csv读取日期和时间? [复制]
【发布时间】:2019-07-30 13:12:33
【问题描述】:
我在时间序列日期时间解析函数中遇到错误。数据为attached。我试过这个来阅读日期和时间列。
Data = pd.read_csv('Data.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
【问题讨论】:
标签:
python
pandas
datetime
timestamp
time-series
【解决方案1】:
strptime() 函数的格式需要与时间戳的格式完全相同,包括斜杠和冒号。您可以在the python documentation找到详细信息。
在这种情况下,您的时间戳格式为1/1/2016 0:00,但您的字符串格式"%Y-%m-%d %H:%M" 是2016-1-1 0:00。如果您使用'%d/%m/%Y %H:%M' 作为格式字符串,那么strptime() 函数将按预期工作。例如:
import datetime as dt
with open('datac.csv','r') as file:
for line in file:
try:
time = line.split(',')[0] #splits the line at the comma and takes the first bit
time = dt.datetime.strptime(time, '%d/%m/%Y %H:%M')
print(time)
except:
pass
您应该能够考虑到这一点来调整您的代码。