将datetime对象转换为date和datetime2,然后将其合并为单列

时间:2017-12-19 18:48:10

标签: python-3.x pandas datetime

我有一个数据集,其中交易日期存储为YYYY-MM-DD 00:00:00,交易时间存储为1900-01-01 HH:MM:SS

我需要截断这些时间戳,然后保持原样或转换为单数时间戳。我尝试了几种方法,并继续返回完整的时间戳。想法?

1 个答案:

答案 0 :(得分:0)

使用splitpd.to_datetime

df = pd.DataFrame({'TransDate':['2015-01-01 00:00:00','2015-01-02 00:00:00','2015-01-03 00:00:00'],
                   'TransTime':['1900-01-01 07:00:00','1900-01-01 08:30:00','1900-01-01 09:45:15']})

df['Date'] = (pd.to_datetime(df['TransDate'].str.split().str[0] + 
              ' ' +
              df['TransTime'].str.split().str[1]))

输出:

             TransDate            TransTime                Date
0  2015-01-01 00:00:00  1900-01-01 07:00:00 2015-01-01 07:00:00
1  2015-01-02 00:00:00  1900-01-01 08:30:00 2015-01-02 08:30:00
2  2015-01-03 00:00:00  1900-01-01 09:45:15 2015-01-03 09:45:15

print(df.info())

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
TransDate    3 non-null object
TransTime    3 non-null object
Date         3 non-null datetime64[ns]
dtypes: datetime64[ns](1), object(2)
memory usage: 152.0+ bytes
None