This question already has answers here:
Splitting timestamp column into separate date and time columns
                                
                                    (7个答案)
                                
                        
                                去年关闭。
            
                    
我有一个从excel导入到熊猫的数据集。字符串格式有一列日期和时间。

16-MAR-16 11.35.27.000000000 AM
05-APR-16 05.21.14.000000000 PM
16-FEB-16 09.56.36.000000000 AM
16-MAR-16 11.35.27.000000000 AM
16-MAR-16 09.28.11.000000000 AM
19-MAY-16 03.50.38.000000000 PM


我想将此数据分为日期和时间,分为不同的列。我遇到了两个相同的问题,但找不到答案。

我尝试过的代码

(1)df["timestamp"] = pd.to_datetime(df['Invoice Date'],dayfirst = True)

(Error)File "C:\Users\admin\Anaconda3\lib\site-packages\dateutil\parser.py", line 559, in parse
raise ValueError("Unknown string format")
ValueError: Unknown string format


(2)from datetime import datetime

df["timestamp"] = df["Invoice Date"].apply(lambda x: datetime.strptime(x,"dd-mmm-yy hh.mm.ss.%f aa"))

(Error)  ValueError: time data '16-MAR-16 11.35.27.000000000 AM' does not match format 'dd-mmm-yy hh.mm.ss.%f aa'


请在这里帮助我。

最佳答案

使用参数formatreference

df["timestamp"] = pd.to_datetime(df['Invoice Date'], format='%d-%b-%y %H.%M.%S.%f %p')
print (df)

                      Invoice Date           timestamp
0  16-MAR-16 11.35.27.000000000 AM 2016-03-16 11:35:27
1  05-APR-16 05.21.14.000000000 PM 2016-04-05 05:21:14
2  16-FEB-16 09.56.36.000000000 AM 2016-02-16 09:56:36
3  16-MAR-16 11.35.27.000000000 AM 2016-03-16 11:35:27
4  16-MAR-16 09.28.11.000000000 AM 2016-03-16 09:28:11
5  19-MAY-16 03.50.38.000000000 PM 2016-05-19 03:50:38


如果需要2个单独的日期和时间列:

d = pd.to_datetime(df['Invoice Date'], format='%d-%b-%y %H.%M.%S.%f %p')
df['date'] = d.dt.date
df['time'] = d.dt.time
print (df)

                      Invoice Date        date      time
0  16-MAR-16 11.35.27.000000000 AM  2016-03-16  11:35:27
1  05-APR-16 05.21.14.000000000 PM  2016-04-05  05:21:14
2  16-FEB-16 09.56.36.000000000 AM  2016-02-16  09:56:36
3  16-MAR-16 11.35.27.000000000 AM  2016-03-16  11:35:27
4  16-MAR-16 09.28.11.000000000 AM  2016-03-16  09:28:11
5  19-MAY-16 03.50.38.000000000 PM  2016-05-19  03:50:38

关于python - 如何从字符串中分割日期和时间? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48637559/

10-09 20:36