如何从python中的csv中读取日期和时间?

时间:2019-03-08 13:33:21

标签: python datetime timestamp time-series

我在时间序列日期-时间解析功能中遇到错误。数据为attached。我试图读取“日期和时间”列。

# date-time parsing function for loading the dataset

def parser(x):
    return datetime.strptime('2016'+x, "%Y-%m-%d %H:%M")
Data = read_csv('Data.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)

enter image description here

1 个答案:

答案 0 :(得分: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

您应该能够牢记这一点。

相关问题