Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

| **original date** | **date**     | **time** | 
41516.43              30/08/2013      10:13:26 AM
like image 883
yoshiserry Avatar asked Mar 14 '14 02:03

yoshiserry


People also ask

How do I convert a date in Excel to a date in python?

xldate_as_datetime() function is used to convert excel date/time number to datetime. datetime object. Parameters: This function accepts two parameters that are illustrated below: xldate: This is the specified excel date that will converted into datetime.


1 Answers

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.

like image 133
Andy Hayden Avatar answered Sep 22 '22 14:09

Andy Hayden