如何分割日期和时间并创建单独的列

时间:2017-05-11 14:05:15

标签: python pandas datetime dataframe

我想拆分 DATE_H_REAL 并创建两列。一个日期和一个小时,我用这个:

from datetime import datetime
df_picru = datetime.strptime(df_picru['DATE_H_REAL'], '%Y-%m-%d %H:%M:%S')
df_picru['day'] = df_picru.strftime('%Y-%m-%d')
df_picru['hour'] = df_picru.strftime('%H:%M:%S')

我的数据看起来像这样

0                      NaN
1                      NaN
2                      NaN
3        02/02/2016 16:16
4        02/02/2016 16:17
5        02/02/2016 16:18

1 个答案:

答案 0 :(得分:1)

在pandas中需要to_datetime + Series.dt.strftime - 如果需要输出strings

df_picru = pd.DataFrame({'DATE_H_REAL':['02/02/2016 16:16',
                                        '02/02/2016 16:17', np.nan]})

df_picru['DATE_H_REAL'] = pd.to_datetime(df_picru['DATE_H_REAL'])
df_picru['day'] = df_picru['DATE_H_REAL'].dt.strftime('%Y-%m-%d')
df_picru['hour'] = df_picru['DATE_H_REAL'].dt.strftime('%H:%M:%S')
print (df_picru)
          DATE_H_REAL         day      hour
0 2016-02-02 16:16:00  2016-02-02  16:16:00
1 2016-02-02 16:17:00  2016-02-02  16:17:00
2                 NaT         NaT       NaT

print (type(df_picru.loc[0, 'day']))
<class 'str'>

print (type(df_picru.loc[0, 'hour']))
<class 'str'>

print (df_picru['DATE_H_REAL'].dtypes)
datetime64[ns]

Series.dt.date + Series.dt.time如果需要输出python datepython time

df_picru['DATE_H_REAL'] = pd.to_datetime(df_picru['DATE_H_REAL'])
df_picru['day'] = df_picru['DATE_H_REAL'].dt.date
df_picru['hour'] = df_picru['DATE_H_REAL'].dt.time
print (df_picru)
          DATE_H_REAL         day      hour
0 2016-02-02 16:16:00  2016-02-02  16:16:00
1 2016-02-02 16:17:00  2016-02-02  16:17:00
2                 NaT         NaN       NaN

print (type(df_picru.loc[0, 'day']))
<class 'datetime.date'>

print (type(df_picru.loc[0, 'hour']))
<class 'datetime.time'>

print (df_picru['DATE_H_REAL'].dtypes)
datetime64[ns]