pythonRcpp
pythonRcpp

Reputation: 2146

Generate interval based timestamps in python

What could be a good way to generate timestamp series for 5 minute interval with a start time of say 09:10:00 and end time of 15:30:00

I know I could hard-code it like below (with all entries, but there must be a clean way where I can just give interval.

times=[pd.to_datetime(i).time() for i in '10:15:00','10:15:05','10:15:10','10:15:15','10:15:20','15:25:00','15:30:00']

I tried

datetime_range(datetime.time(09,15,00), datetime.time(15,30,00),  timedelta(minutes=5))

But this gives SyntaxError: invalid token

Upvotes: 1

Views: 7798

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226199

What could be a good way to generate timestamp series for 5 minute interval with a start time of say 09:10:00 and end time of 15:30:00

A simple loop should do the trick:

from datetime import datetime, time, timedelta

times = []
ts = datetime(2017, 7, 17, 9, 10, 0)
while ts <= datetime(2017, 7, 17, 15, 30, 0):
    times.append(time(ts.hour, ts.minute, ts.second))
    ts += timedelta(minutes=5)

The reason for using datetime objects to start with is that they support timedelta objects which make short work of your problem. From there, it is easy to convert to a time object with time(ts.hour, ts.minute, ts.second).

Upvotes: 0

Cory Madden
Cory Madden

Reputation: 5193

How about this?

times = [(datetime.datetime(2017, 7, 17, 9, 10, 0) + datetime.timedelta(minutes=5*x)).time() for x in range(5)]

It's a little long, but it all fits on one line like it looks like you want to do. Of course you can work around that with importing the functions you need instead of the whole module.

Upvotes: 3

Related Questions