Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date/time in Pandas

Tags:

python

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?

like image 275
vgoklani Avatar asked Dec 08 '22 22:12

vgoklani


2 Answers

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)
    )
like image 110
vgoklani Avatar answered Dec 23 '22 21:12

vgoklani


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')
like image 41
jdmarino Avatar answered Dec 23 '22 22:12

jdmarino