pandas:为日期,分钟

时间:2017-03-01 04:12:46

标签: python-2.7 pandas datetime

我想通过设置年,月,日和分钟,秒的常量来创建新的datetime列,仅保留

import pandas as pd
td = pd.DataFrame(['2015-01-01 09:03:00', '2015-01-11 15:47:00', 
            '2015-01-11 16:47:00', '2015-01-11 01:47:00', '2016-01-11 01:47:00'], columns=['datetime'])
td['datetime'] = pd.to_datetime(td['datetime'])


    datetime
0   2015-01-01 09:03:00
1   2015-01-11 15:47:00
2   2015-01-11 16:47:00
3   2015-01-11 01:47:00
4   2016-01-11 01:47:00

结果应如下所示。

    datetime
0   1900-01-01 09:00:00
1   1900-01-01 15:00:00
2   1900-01-01 16:00:00
3   1900-01-01 01:00:00
4   1900-01-01 01:00:00

我该如何编码呢?谢谢!

2 个答案:

答案 0 :(得分:2)

使用pd.to_timedelta

pd.to_datetime('1900-01-01') + pd.to_timedelta(td.datetime.dt.hour, unit='H')

0   1900-01-01 09:00:00
1   1900-01-01 15:00:00
2   1900-01-01 16:00:00
3   1900-01-01 01:00:00
4   1900-01-01 01:00:00
Name: datetime, dtype: datetime64[ns]

答案 1 :(得分:1)

td['datetime'].apply(lambda x: datetime(1900, 1, 1) + timedelta(hours=x.hour))

0   1900-01-01 09:00:00
1   1900-01-01 15:00:00
2   1900-01-01 16:00:00
3   1900-01-01 01:00:00
4   1900-01-01 01:00:00
Name: datetime, dtype: datetime64[ns]