Merlin
Merlin

Reputation: 25639

How you create a datetime index in pandas

How do I create an datetime index "foo" to use with raw data series. (Example would "as of" every 15 seconds 'foo' and and every 30 seconds 'foo2'.) If raw series can be inserted into a 'base' dataframe, I would like to use 'foo' to recast the dataframe.

If wanted series to combine combine df "foo" and df "foo2", what would be the memory hits Would it be better to fill the foo index with the raw data series.

EDIT: after import pandas , datetime.timedelta stops working

Upvotes: 2

Views: 8513

Answers (3)

David
David

Reputation: 128

as of version 0.24

Creating a DatetimeIndex based on start, periods, and end has been deprecated in favor of date_range().

Using date_range() is similar to DatetimeIndex()

start = datetime.datetime.now()
end = start + datetime.timedelta(hours=1)
times = pd.date_range(freq='2s', start=start, end=end)

times is a DatetimeIndex with 1801 elements with an interval of 2 seconds

Upvotes: 1

Jason
Jason

Reputation: 4546

Since Wes' answer I think pandas.DateRange is no longer present in pandas. I'm on pandas version 0.22.0.

I used pandas.DatetimeIndex instead, e.g.:

import datetime
import pandas as pd


start = datetime.datetime.now()
times = pd.DatetimeIndex(freq='2s', start=start, periods=10)

or alternatively

start = datetime.datetime.now()
end = start + datetime.timedelta(hours=1)
times = pd.DatetimeIndex(freq='2s', start=start, end=end)

Upvotes: 2

Wes McKinney
Wes McKinney

Reputation: 105491

It's very hard for me to understand what you're asking; an illustration of exactly what you're looking for, with example data, would help make things more clear.

I think what you should do:

rng = DateRange(start, end, offset=datetools.Second(15)

to create the date range. To put data in a DataFrame indexed by that, you should add the columns and reindex them to the date range above using method='ffill':

df = DataFrame(index=rng)
df[colname] = series.reindex(df.index, method='ffill')

Per datetime.timedelta, datetime.datetime is part of the pandas namespace, so if you did from pandas import * then any import datetime you had done before that would be masked by the datetime.datetime reference inside the pandas namespace.

Upvotes: 7

Related Questions