Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

python - Efficient way of making time increment strings?

I want to create a list of time slots (as a string). What is the most efficient way of doing this with python?

This list would go from 8:00am to 10pm in 15 minute increments. I want a list that is formatted like this:

['8:00am - 8:15am', '8:15am - 8:30am', '8:30am - 8:45am',.......] 

I attempted using several for loops nested together until it got very complicated and I knew there must be a better, more pythonic way of doing something like this.

Anyone have any ideas?

question from:https://stackoverflow.com/questions/65874794/efficient-way-of-making-time-increment-strings

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Like @juanpa.arrivillaga's answer, but with formatting:

from datetime import datetime, timedelta
t = datetime(1, 1, 1, hour=8, minute=0)
l = []
while t < datetime(1, 1, 1, hour=22, minute=1):
    l.append(t.strftime('%I:%M%p') + " - " + (t+timedelta(minutes=15)).strftime('%I:%M%p'))
    t += timedelta(minutes=15)

print(l)
>>>
['08:00AM - 08:15AM', '08:15AM - 08:30AM', '08:30AM - 08:45AM', '08:45AM - 09:00AM', '09:00AM - 09:15AM', '09:15AM - 09:30AM', '09:30AM - 09:45AM', '09:45AM - 10:00AM', '10:00AM - 10:15AM', '10:15AM - 10:30AM', '10:30AM - 10:45AM', '10:45AM - 11:00AM', '11:00AM - 11:15AM', '11:15AM - 11:30AM', '11:30AM - 11:45AM', '11:45AM - 12:00PM', '12:00PM - 12:15PM', '12:15PM - 12:30PM', '12:30PM - 12:45PM', '12:45PM - 01:00PM', '13:00PM - 01:15PM', '13:15PM - 01:30PM', '13:30PM - 01:45PM', '13:45PM - 02:00PM', '14:00PM - 02:15PM', '14:15PM - 02:30PM', '14:30PM - 02:45PM', '14:45PM - 03:00PM', '15:00PM - 03:15PM', '15:15PM - 03:30PM', '15:30PM - 03:45PM', '15:45PM - 04:00PM', '16:00PM - 04:15PM', '16:15PM - 04:30PM', '16:30PM - 04:45PM', '16:45PM - 05:00PM', '17:00PM - 05:15PM', '17:15PM - 05:30PM', '17:30PM - 05:45PM', '17:45PM - 06:00PM', '18:00PM - 06:15PM', '18:15PM - 06:30PM', '18:30PM - 06:45PM', '18:45PM - 07:00PM', '19:00PM - 07:15PM', '19:15PM - 07:30PM', '19:30PM - 07:45PM', '19:45PM - 08:00PM', '20:00PM - 08:15PM', '20:15PM - 08:30PM', '20:30PM - 08:45PM', '20:45PM - 09:00PM', '21:00PM - 09:15PM', '21:15PM - 09:30PM', '21:30PM - 09:45PM', '21:45PM - 10:00PM', '22:00PM - 10:15PM']

If you can use pandas, here's a shorter answer:

import pandas as pd

dr = pd.date_range('2021-01-01 08:00', '2021-01-01 22:00', freq='15min')
l = [t.strftime('%I:%M%p') + " - " + (t+pd.to_timedelta('15min')).strftime('%I:%M%p') for t in dr]

Edit: Edited the code according to @Shash Sinha's comment below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...