pandas 将datatime列转换为时间戳 [英] pandas convert datatime column to timestamp

查看:172
本文介绍了 pandas 将datatime列转换为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是熊猫的初学者

我有dataframe第一列是datatime之类的"19-Sep-2016 10:30:00",并且有很多类似的记录.

I have dataframe first column is datatime like "19-Sep-2016 10:30:00" and many records like it.

我正在尝试将此列转换为时间戳并将其写入另一个数据帧,我试图一步实现.

I am trying to convert this column to timestamp and write it to another dataframe , i am trying to do it with one step.

我正在尝试用python 3编写.

I am trying to write in python 3.

import pandas as pd
import time
from time import strptime

xl = pd.ExcelFile(file)
df = xl.parse(sheetname=0)
our_df['DateTime'] = int(time.mktime(time.strptime(df['Date Time'], "%d-%b-%Y %H:%M:%S")))

但是我有错误:

TypeError: strptime() argument 0 must be str, not <class 'pandas.core.series.Series'>

我正在尝试搜索它,但是我花了很长时间没有收益.

I am trying to google it but I take long time without benefits.

现在,我该怎么做正确的方法?

Now, how can I do it the right way?

推荐答案

您可以使用 to_datetime :

You can use to_datetime:

df = pd.DataFrame({'DateTime':['19-Sep-2016 10:30:00','19-Sep-2016 10:30:00']})
print (df)
               DateTime
0  19-Sep-2016 10:30:00
1  19-Sep-2016 10:30:00

df['DateTime'] = pd.to_datetime(df['DateTime'])
print (df)
             DateTime
0 2016-09-19 10:30:00
1 2016-09-19 10:30:00

如果要指定格式:

df['DateTime'] = pd.to_datetime(df['DateTime'], format='%d-%b-%Y %H:%M:%S')
print (df)
             DateTime
0 2016-09-19 10:30:00
1 2016-09-19 10:30:00

对于times,添加 dt.time :

And for times add dt.time:

df['DateTime'] = pd.to_datetime(df['DateTime']).dt.time
print (df)
   DateTime
0  10:30:00
1  10:30:00

然后可以使用 join -数据按索引值对齐,如果长度不同,则将NaT s作为最后一个值:

Then is possible use join - data are aligned by index values, if length is different get NaTs as last values:

df1 = pd.DataFrame({'Col':[5, 4, 0, 7]})
print (df1)
   Col
0    5
1    4
2    0

df1 = df1.join(pd.to_datetime(df['DateTime']))
print (df1)
   Col            DateTime
0    5 2016-09-19 10:30:00
1    4 2016-09-19 10:30:00
2    0                 NaT
3    7                 NaT

df1['DateTime'] = pd.to_datetime(df['DateTime'])
print (df1)
   Col            DateTime
0    5 2016-09-19 10:30:00
1    4 2016-09-19 10:30:00
2    0                 NaT
3    7                 NaT


df1 = df1.join(pd.to_datetime(df['DateTime']).dt.time)
print (df1)
   Col  DateTime
0    5  10:30:00
1    4  10:30:00
2    0       NaN
3    7       NaN

df1['DateTime'] = pd.to_datetime(df['DateTime']).dt.time
print (df1)
   Col  DateTime
0    5  10:30:00
1    4  10:30:00
2    0       NaN
3    7       NaN

这篇关于 pandas 将datatime列转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆