将文本合并到datetime列

时间:2017-02-02 13:13:21

标签: python pandas datetime

我有一个包含2列的数据框。 String[] header = { " Book Title", "Book Description", " Book Author", "Book Publisher", "Book isbn", "Book PublishedDate", "Book Price" }; String[] fieldMapping = new String[] { "title", "description", "author", "publisher", "isbn", "publishedDate", "price"}; csvWriter.writeHeader(header); for (Book aBook : listBooks) csvWriter.write(aBook, fieldMapping); col1datecol2。 有虚拟值bigint1970-01-01 00:00:00

19700101000000

我正在寻找一种方法将这两列合并到一个像这样的日期时间列......

col1                col2
2012-01-12 18:09:42 19700101000000
1970-01-01 00:00:00 20140701000001

或者有没有办法将列col2中的文本合并到col1。

1 个答案:

答案 0 :(得分:1)

您需要先to_datetime然后to_timedelta,最后添加到col1

print (pd.to_datetime(df.col2, format='%Y%m%d%H%M%S'))
0   1970-01-01 00:00:00
1   2014-07-01 00:00:01
Name: col2, dtype: datetime64[ns]

print (pd.to_timedelta(pd.to_datetime(df.col2, format='%Y%m%d%H%M%S')))
0       0 days 00:00:00
1   16252 days 00:00:01
Name: col2, dtype: timedelta64[ns]

df.col1 = pd.to_datetime(df.col1)
df['col3'] = pd.to_timedelta(pd.to_datetime(df.col2, format='%Y%m%d%H%M%S')) + df.col1
print (df)
                 col1            col2                col3
0 2012-01-12 18:09:42  19700101000000 2012-01-12 18:09:42
1 1970-01-01 00:00:00  20140701000001 2014-07-01 00:00:01

也可以使用参数unit

df['col3'] = pd.to_timedelta(pd.to_datetime(df.col2, format='%Y%m%d%H%M%S'), unit='ns') + 
             df.col1
print (df)
                 col1            col2                col3
0 2012-01-12 18:09:42  19700101000000 2012-01-12 18:09:42
1 1970-01-01 00:00:00  20140701000001 2014-07-01 00:00:01