pandas 将日期时间列拆分为日期和时间 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24813673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:16:25  来源:igfitidea点击:

Split Datetime Column into a Date and Time Python

pythondatetimepandassplit

提问by Alexis

Hey so I have seen several questions about this, however, I have yet to successful solve my problem.

嘿所以我已经看到了几个关于这个的问题,但是,我还没有成功解决我的问题。

I have a single column Time in the format:

我有一个单列时间的格式:

2014-07-17 00:59:27.400189+00

2014-07-17 00:59:27.400189+00

I want to split this into a two columns, Date and Hour.

我想把它分成两列,日期和小时。

I used

我用了

 posts['Date']=pd.to_datetime(posts['Time'],format='%Y-%m-%d %H:%M:%S')

However, I get an error

但是,我收到一个错误

 ValueError: unconverted data remains: 400189+00

I am not sure what to label the last bit of information. I tried added %o but received another error

我不确定最后一点信息要标记什么。我尝试添加 %o 但收到另一个错误

 ValueError: 'o' is a bad directive in format '%Y-%m-%d %H:%M:%S.%o'

Any ideas on how I can split these two values into two columns?

关于如何将这两个值分成两列的任何想法?

Thanks!

谢谢!

回答by EdChum

the following worked for me:

以下对我有用:

In [18]:

import pandas as pd
df = pd.DataFrame({'Date':['2014-07-17 00:59:27.400189+00']})
df.dtypes
Out[18]:
Date    object
dtype: object
In [19]:

df['Date'] = pd.to_datetime(df['Date'])
df.dtypes
Out[19]:
Date    datetime64[ns]
dtype: object
In [20]:

df['Time'],df['Date']= df['Date'].apply(lambda x:x.time()), df['Date'].apply(lambda x:x.date())
df
Out[20]:
         Date             Time
0  2014-07-17  00:59:27.400189

[1 rows x 2 columns]

回答by Okroshiashvili

This worked for me

这对我有用

import pandas as pd 

data = pd.DataFrame({'Date':['2014-07-17 00:59:27.400189+00']})

data['Dates'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.date
data['Hours'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.time

You have to have

你必须有

print(data)

Dates           Hours
2014-07-17     00:59:27.400189+00

回答by Reshma2k

import pandas as pd 

data = pd.DataFrame({'Date':['2014-07-17 00:59:27.400189+00']})

data['Dates'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.date
data['Hours'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.time

This gives me object type Date and Time. The expected column should be in date format

这给了我对象类型日期和时间。预期的列应该是日期格式