1

I have to create a two slot based on the current time assume that current time is 11:25 so based on the current time i have to create two slot for 30 minutes of time period which suppose to be 11:00 to 11:30 and another one is 11:30 to 12:00 and these slot should be dynamic so if the time is 12:20 then my new slot should be 12:00 to 12:30 and 12:30 to 1:00 only two slots using python.

I am newbie to python any help would be appreciated.

todayDate = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(todayDate)
currentTime = datetime.now()
now= 30

As I told i am newbie to python i have tried this much and stuck to logic.

Matthew Miles
  • 727
  • 12
  • 26

1 Answers1

0

You can use the Pandas module. Specifically the date_range function.

import pandas

# Get current time
now = pandas.Timestamp.now()    

# Round current time down to the nearest 30 minutes.
now = now.floor('30min')

# create a range of 3 datetime objects with a frequency of 30 minutes.
datetimes = pandas.date_range(start=now, periods=3, freq='30min')

# Get only the Hour and Minute of those datetime objects.
times = [datetime.strftime("%H:%M") for datetime in datetimes]

# Use list slicing to repeat second time.
times = times[:2] + times[1:]

print(times)

returns

['12:00', '12:30', '12:30', '13:30']

When run any time between 12:00 and 12:29.

Linden
  • 531
  • 3
  • 12
  • Hii @Linden thanks for the help and the code is working fine but i want output as ['12:00', '12:30', '12:30', '13:00'] and if the current time is 12:30 i want output as ['12:30', '13:00', '13:00', '13:30'] . – Shahid Shaikh Mar 30 '22 at 11:54
  • I have edited my answer. You can get 3 periods instead of 4 and use list slicing to repeat the middle time. – Linden Mar 30 '22 at 12:16
  • The code is working according to my requirements, Thank you so much for helping me out. – Shahid Shaikh Mar 31 '22 at 04:47
  • You're welcome. If you do a lot of work with dates and times, (or data manipulation in general) the pandas module is well worth reading up on. You can accept my answer if you're happy with it, but someone else may be able to suggest something better. – Linden Mar 31 '22 at 06:52