some_programmer
some_programmer

Reputation: 3528

How to generate a time series data for a month with a gap of 1 second using pandas?

I am generating dates between 01-01-2010 and 31-01-2010 with a gap of 1 second as follows:

import datetime
dt = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2010, 1, 31, 23, 59, 59)
step = datetime.timedelta(seconds=1)

result = []

while dt < end:
    result.append(dt.strftime('%Y-%m-%d %H:%M:%S'))
    dt += step

and the result that it gives it perfectly fine, but it takes about 10secs to give the result.

I was wondering if the same can be achieved using pandas so that it can be achieved a bit quickly

Upvotes: 2

Views: 241

Answers (2)

jezrael
jezrael

Reputation: 862471

Use date_range with DatetimeIndex.strftime:

result = pd.date_range(dt, end, freq='S').strftime('%Y-%m-%d %H:%M:%S').tolist()

Or:

result = pd.date_range('2010-01-01',
                       '2010-01-30 23:59:59',freq='S').strftime('%Y-%m-%d %H:%M:%S').tolist()

Upvotes: 1

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 32003

try like below

l = (pd.DataFrame(columns=['NULL'],
                  index=pd.date_range('2010-01-01T00:00:00Z', '2010-01-31T00:00:00Z',
                                      freq='1T'))

       .index.strftime('%Y-%m-%dT%H:%M:%SZ')
       .tolist()
)

print(l)

Upvotes: 1

Related Questions