将数据框的列转换为时间戳

时间:2018-12-03 11:55:25

标签: python-datetime

我正在将数据框读入熊猫。它是来自ECG的时间序列数据。我有两列:第一列是获取读数的时间,第二列是来自ECG的值。我正在尝试将第一列转换为时间戳并将其用作索引。我的代码如下:

import pandas as pd
from datetime import datetime
from datetime import time
import matplotlib.pyplot as plt
path='/home/user_1/Documents/heart_data.csv'
df=pd.read_csv(path)
df.columns=['Elapsed Time','i']
df['Elapsed Time']=pd.to_datetime(df['Elapsed Time'], format="'%H:%M.%S%f'") 
df.set_index('Elapsed Time', inplace=True)
print(df.head())

我的问题是,这给了我列格式为'1900-01-01 00:00:00.000'的输出,但是我不希望只是时间为'1900-01-01'。 如何摆脱列中显示的日期?

1 个答案:

答案 0 :(得分:0)

#Let's create a dataframe.
df=pd.DataFrame({'date':['1920-01-01 00:00:00.000','1900-01-01 22:00:00.000']},index=[1,2])
df['date']=pd.to_datetime(df['date'],format='%Y-%m-%d %H:%M:%S.%f')
df
                 date
1 1920-01-01 00:00:00
2 1900-01-01 22:00:00

df=df['date'].dt.time #This will only give you Time part

df
1    00:00:00
2    22:00:00
Name: date, dtype: object