Dave X
Dave X

Reputation: 5127

Create Pandas DatetimeIndex from origin and offsets

I want to convert a set of seconds into a Pandas index suitable for a dataframe.

I think I'm looking for the inverse of the dt.total_seconds() operation as in the https://stackoverflow.com/a/36156620/1653571 answer to Accessing total_seconds() in pandas data column

Given:

t0="2010-10-01 00:00:00 UTC"
seconds = [0,1,2,3,5,7,11,13]

I want something like:

ii = pd.DatetimeIndex( ???(t0,seconds))

Upvotes: 1

Views: 126

Answers (1)

cs95
cs95

Reputation: 402273

Convert the seconds list to Timedelta and do a little datetime arithmetic.

# origin           + offset
pd.to_datetime(t0) + pd.to_timedelta(seconds, unit='s')

DatetimeIndex(['2010-10-01 00:00:00+00:00', '2010-10-01 00:00:01+00:00',
               '2010-10-01 00:00:02+00:00', '2010-10-01 00:00:03+00:00',
               '2010-10-01 00:00:05+00:00', '2010-10-01 00:00:07+00:00',
               '2010-10-01 00:00:11+00:00', '2010-10-01 00:00:13+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)

Upvotes: 3

Related Questions