Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Excel style date with pandas

Tags:

I have to parse an xml file which gives me datetimes in Excel style; for example: 42580.3333333333.

Does Pandas provide a way to convert that number into a regular datetime object?

like image 451
sascha_luen Avatar asked Jul 19 '16 09:07

sascha_luen


People also ask

How do I change the date format in Excel pandas?

Pandas does not change the Date format WITHIN Excel. If you want to do that, then you should use openpyxl and create a writer object and pass the date_format . In case someone says this, you CANNOT simply do: pd. to_datetime(table['Effective Date'], format='%d %b %Y', errors='coerce').

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

OK I think the easiest thing is to construct a TimedeltaIndex from the floats and add this to the scalar datetime for 1900,1,1:

In [85]:
import datetime as dt
import pandas as pd
df = pd.DataFrame({'date':[42580.3333333333, 10023]})
df

Out[85]:
           date
0  42580.333333
1  10023.000000

In [86]:
df['real_date'] = pd.TimedeltaIndex(df['date'], unit='d') + dt.datetime(1900,1,1)
df

Out[86]:
           date                  real_date
0  42580.333333 2016-07-31 07:59:59.971200
1  10023.000000 1927-06-12 00:00:00.000000

OK it seems that excel is a bit weird with it's dates thanks @ayhan:

In [89]:
df['real_date'] = pd.TimedeltaIndex(df['date'], unit='d') + dt.datetime(1899, 12, 30)
df

Out[89]:
           date                  real_date
0  42580.333333 2016-07-29 07:59:59.971200
1  10023.000000 1927-06-10 00:00:00.000000

See related: How to convert a python datetime.datetime to excel serial date number

like image 67
EdChum Avatar answered Nov 07 '22 04:11

EdChum