CSV文件转换为Pandas Series(时间对象)

时间:2019-05-17 06:27:15

标签: python pandas

首先,我有一个像这样的0404.csv

"time","xxxxx","xxxxxxx"

"09:00:00","xxxx","xxxxxx"

"09:00:01","xxxxx","xxxxx"

"09:00:02","xxxxxx","xxxxxx"
..........
我想获得一系列datetime,例如datetime.datetime(2019,4,4,9,0,1)datetime.datetime(2019,4,4,9,0,2)......

import pandas as pd  
df = pd.read_csv("0404.csv", usecols = ['time'])

1 个答案:

答案 0 :(得分:0)

好吧,由于您的时间列仅包含时间,因此您无法从中提取日期

       time
0  09:00:00
1  09:00:01
2  09:00:02

所以您需要自己制作,就像这样:

import pandas as pd
import datetime

df = pd.read_csv("0404.csv", usecols = ['time'])

df['time'] = df['time'].apply(lambda x: datetime.datetime.strptime('2019-04-04 {}'.format(x), '%Y-%m-%d %H:%M:%S'))

输出将如下所示:

                 time
0 2019-04-04 09:00:00
1 2019-04-04 09:00:01
2 2019-04-04 09:00:02