Reputation: 1605
I am trying to understand python datetime
module. I want to increase the time by 5min between two intervals. This is what I did,
import datetime
start_time = datetime.datetime(100,1,1,8,0,0) # 8am
end_time = datetime.datetime(100,1,1,9,00,0) # 9am
delta_time = datetime.timedelta(0,300) # 5min intervals
new_time = start_time + delta_time
print(new_time.time())
this gives 08:05:00
. I want the result as follow,
08:05:00
08:10:00
08:15:00
How to get the rest of the time in simpler way? I am getting an error if I use a for loop.
Upvotes: 0
Views: 189
Reputation: 3429
It is simple by using the range
function and converting minutes to seconds and vice versa.
The code uses a generator expression to get a series of the datetime objects, not a list comprehension. If it needed to understand the difference between them, it is very easy to find tons of information about this on Stack Overflow.
from pprint import pprint # https://docs.python.org/3.5/library/pprint.html#pprint.pprint
from datetime import datetime, timedelta
f = '%m/%d/%Y:%H:%M:%S'
beg, fin = [datetime.strptime(d, f) for d in ['10/25/2015:00:00:05', '10/25/2015:23:59:58']]
step = 5 # minutes
ts = (beg + timedelta(minutes=s // 60) for s in range(0, int((fin - beg).total_seconds() + 1), step * 60))
pprint([t.strftime(f) for t in ts])
Output:
['10/25/2015:00:00:05',
'10/25/2015:00:05:05',
'10/25/2015:00:10:05',
...
'10/25/2015:23:45:05',
'10/25/2015:23:50:05',
'10/25/2015:23:55:05']
Demo.
Upvotes: 1
Reputation: 2342
Here is one approach:
import datetime
h=8 # The starting hour
end_h=10 #the ending hour
m=0
delta=5 #delta value
while h<end_h:
if m>55:
h+=1
m=0
new_time=datetime.datetime(100,1,1,h,m,0)
print(new_time.time())
m=m+delta
Output:
08:00:00
08:05:00
08:10:00
08:15:00
08:20:00
08:25:00
08:30:00
08:35:00
08:40:00
08:45:00
08:50:00
08:55:00
09:00:00
09:05:00
09:10:00
09:15:00
09:20:00
09:25:00
09:30:00
09:35:00
09:40:00
09:45:00
09:50:00
09:55:00
10:00:00
Limitation: This technique works for a max value of end_h=24.
Upvotes: 1
Reputation: 11
If you want to do this using datetime
, try while
loop as follows:
import datetime
start_time = datetime.datetime(100,1,1,8,0,0) # 8am
end_time = datetime.datetime(100,1,1,9,00,0) # 9am
delta_time = datetime.timedelta(0, 300) # 5min intervals
new_time = start_time
while new_time != end_time:
new_time += delta_time
print(new_time.time())
This is what you'll get:
08:05:00
08:10:00
08:15:00
08:20:00
08:25:00
08:30:00
08:35:00
08:40:00
08:45:00
08:50:00
08:55:00
09:00:00
Upvotes: 1
Reputation: 29742
One way using pandas.date_range
:
import pandas as pd
t_series = pd.date_range('08:05:00', '09:00:00', freq='5 min')
If you want only the time (just as demonstrated), use pandas.Series.dt.time
:
for t in t_series.to_series().dt.time:
print(t)
Output:
08:05:00
08:10:00
08:15:00
08:20:00
08:25:00
08:30:00
08:35:00
08:40:00
08:45:00
08:50:00
08:55:00
09:00:00
Upvotes: 2