Issue
I have two times and I want to make a list of all the hours between them using the same format in Python .
As I have
start_time: 08:00:00
end_time: 13:00:00
I want to make a list of hours between them. like this from start to end (08:00:00 - 13:00:00).
[
{
start: 08:00:00,
end: 09:00:00
},
{
start: 09:00:00,
end: 10:00:00
},
{
start: 10:00:00,
end: 11:00:00
},
{
start: 11:00:00,
end: 12:00:00
},
{
start: 12:00:00,
end: 13:00:00
}
]
one hour range distributed set between a time range. I'm using pandas but it's quite handy with date distribution but couldn't apply that on time. What can be the efficient way in python, I was wondering.
Solution
You can do:
Note: I m assuming your start_time, end_time are strings
from datetime import datetime
from datetime import timedelta
f = '%H:%M:%S'
begin = datetime.strptime(start_time, f)
end = datetime.strptime(end_time, f)
duration = ((end-begin).seconds) // 3600
out = [{'start': (begin + timedelta(hours=i)).strftime(f),
'end': (begin + timedelta(hours=i + 1)).strftime(f)} for i in
range(duration)]
print(out):
[{'start': '08:00:00', 'end': '09:00:00'},
{'start': '09:00:00', 'end': '10:00:00'},
{'start': '10:00:00', 'end': '11:00:00'},
{'start': '11:00:00', 'end': '12:00:00'},
{'start': '12:00:00', 'end': '13:00:00'}]
Answered By - SomeDude
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.