vgoklani
vgoklani

Reputation: 11786

Converting date/time in Pandas

I have stock ticker data in the following format:

40289.65972
40289.66319
40289.66667

and Excel is able to magically convert them to:

4/22/14 3:50 PM
4/22/14 3:55 PM
4/22/14 4:00 PM

via "Format Cells"

How do I do the same conversion in pandas?

Upvotes: 4

Views: 6807

Answers (3)

jdmarino
jdmarino

Reputation: 545

To stay within pandas (which is wicked fast), use to_timedelta()

import pandas as pd
# should get  7/7/1988 1:26:24 a.m. (https://support.microsoft.com/en-us/kb/214094)
pd.to_datetime('1899-12-30') + pd.to_timedelta(32331.06, 'D')

produces Timestamp('1988-07-07 01:26:24') If you have a dataframe full of excel-float-dates you can convert the whole thing:

df['BetterDT'] = pd.to_datetime('1899-12-30') + pd.to_timedelta(df.ExecDate, 'D')

Upvotes: 5

Alejandro
Alejandro

Reputation: 21

Excel considers 1900 a leap year, so be careful with exactly what you want to translate: http://spreadsheetpage.com/index.php/oddity/the_intentional_date_bug/

Upvotes: 2

vgoklani
vgoklani

Reputation: 11786

The solution mentioned in the link above works, so I will just repost the snippet here. Thanks!

import datetime

def minimalist_xldate_as_datetime(xldate, datemode):
    # datemode: 0 for 1900-based, 1 for 1904-based
    return (
        datetime.datetime(1899, 12, 30)
        + datetime.timedelta(days=xldate + 1462 * datemode)
    )

Upvotes: 7

Related Questions