16

I'm trying to create a new Pandas dataframe column with ordinal day from a datetime column:

import pandas as pd
from datetime import datetime

print df.ix[0:5]
                              date
file                              
gom3_197801.nc 2011-02-16 00:00:00
gom3_197802.nc 2011-02-16 00:00:00
gom3_197803.nc 2011-02-15 00:00:00
gom3_197804.nc 2011-02-17 00:00:00
gom3_197805.nc 2011-11-14 00:00:00

df['date'][0].toordinal()

Out[6]:
734184

df['date'].toordinal()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-dbfd5e8b60f0> in <module>()
----> 1 df['date'].toordinal()

AttributeError: 'Series' object has no attribute 'toordinal'

I guess this is a basic question, but I've struggled reading docs for last 30 minutes.

How can I create an ordinal time column for my dataframe?

Paul H
  • 65,268
  • 20
  • 159
  • 136
Rich Signell
  • 14,842
  • 4
  • 49
  • 77

3 Answers3

29

Use apply:

df['date'].apply(lambda x: x.toordinal())
lowtech
  • 2,492
  • 2
  • 22
  • 31
12

you can also use map:

import datetime as dt
df['date'].map(dt.datetime.toordinal)
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
  • 5
    The timedata is rounded into a integer, For example, I have `2015-12-08 12:13:46.343000` but this is rounded to 735940, how can i get with the decimals? – nandhos Aug 31 '15 at 21:15
3

For completeness:
Apply pd.Timestamp.toordinal

df['date'].apply(pd.Timestamp.toordinal)
wwii
  • 23,232
  • 7
  • 37
  • 77