简体   繁体   English

将日期(excel格式)的数字表示转换为python日期和时间,然后将它们拆分为pandas中的两个单独的dataframe列

[英]convert numerical representation of date (excel format) to python date and time, then split them into two seperate dataframe columns in pandas

I'm importing some data in a spreadsheet. 我正在电子表格中导入一些数据。 It's in a dataframe, but the date is in a numerical representation or format 它位于数据框中,但日期采用数字表示或格式

41516.43

First, I want to convert it to a date and time object 首先,我想将其转换为日期和时间对象

date_val = 30/08/2013  10:13:26 AM

Then I would like to split the date_val into date and time separately, and place them in seperate columns in my dataframe (df) 然后我想分别将date_val分成日期和时间,并将它们放在我的数据框中的单独列中(df)

| **original date** | **date**     | **time** | 
41516.43              30/08/2013      10:13:26 AM

Piecing together from another question : 另一个问题拼凑而成:

In [11]: s = pd.Series([41516.43])

In [12]: from xlrd.xldate import xldate_as_tuple

In [13]: from datetime import datetime

In [14]: s.apply(lambda x: datetime(*xldate_as_tuple(x, 0)))
Out[14]:
0   2013-08-30 10:19:12
dtype: datetime64[ns]

Note: presumably slight difference is due to rounding of the float you gave. 注意:可能是微小的差异是由于您给出的浮子的四舍五入。

and the "bare-knuckle no-seat-belts use-at-own-risk" version: 以及“裸露的无座椅安全带使用自有风险”版本:

In [21]: pd.Timestamp('1899-12-30') + (pd.offsets.Day(1).nanos * s).astype(np.timedelta64)
Out[21]:
0   2013-08-30 10:19:12
dtype: datetime64[ns]

I think it's generally preferable to do parse dates while using read_excel . 我认为通常最好在使用read_excel时进行解析日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM