from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
How can I find the number of 15 minutes intervals exist between start and finish?
from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
elapsed = finish - start
number_of_intervals = elapsed / timedelta(minutes=15)
elapsed is the timedelta between start and finish. Divide by 15 minutes to calculate how many 15 minute intervals fit in there.
Note that this returns a float, so includes fractional intervals. Round as appropriate.
You need to find the difference between start and finish in minutes, divide by 15, and make that an int:
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
difference = (finish - start).total_seconds()/60
quarters = int(difference/15)
i would write something similar to this:
from datetime import datetime, timedelta
DATE_TIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
from_date_time = datetime.strptime('2016-06-06T05:00:00.000Z',
DATE_TIME_STRING_FORMAT)
to_date_time = datetime.strptime('2016-06-06T06:00:00.000Z',
DATE_TIME_STRING_FORMAT)
date_times = [from_date_time.strftime(DATE_TIME_STRING_FORMAT)]
date_time = from_date_time
while date_time < to_date_time:
date_time += timedelta(minutes=15)
date_times.append(date_time.strftime(DATE_TIME_STRING_FORMAT))
print(date_times)
Output:
['2016-06-06T05:00:00.000000Z', '2016-06-06T05:15:00.000000Z', '2016-06-06T05:30:00.000000Z', '2016-06-06T05:45:00.000000Z', '2016-06-06T06:00:00.000000Z']
Edit:
If you are interested in just the number of 15 minute intervals you can use something like:
from datetime import datetime, timedelta
DATE_TIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
from_date_time = datetime.strptime('2016-06-06T05:00:00.000Z',
DATE_TIME_STRING_FORMAT)
to_date_time = datetime.strptime('2016-06-06T06:00:00.000Z',
DATE_TIME_STRING_FORMAT)
print((to_date_time-from_date_time) / timedelta(minutes=15))
You can use time library instead of date time. time works with seconds and you should convert minutes to seconds:
import time
interval = 45*60
start = time.time()
finish = time.time() + interval
diff = finish - start
print(diff // (15*60))
Simply compare start and finish like so:
from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
elapsed = finish - start # This is a timedelta object
reference_interval = 15*60 # interval in seconds
number_of_intervals = elapsed.seconds/reference_interval
As pointed out by Sören, this will not work if 'elapsed' is more than one day, in which case, simply compute the number as follow:
number_of_intervals = (elapsed.days*86400+elapsed.seconds)/reference_interval
# (86400 seconds in a day)
When I run my application , its supposed to play an mp3 file when the current time is equal to one of times in a list. The mp3 file is in the same folder as my python file. However, Three things happen. First, the sound doesn't play even though the time is correct and an output is shown in the terminal indicating that the time comparison is true. Second, an extra tkinter window pops up and finally, when I try to close both of the windows, I get these errors:
time to pray at 03:10 PM
invalid command name "2184036301640calc_countdown"
while executing
"2184036301640calc_countdown"
("after" script)
Traceback (most recent call last):
File "d:\My stuff\mypython\Tkinter\azan caller\azan_caller.py", line 266, in <module>
call_azan()
File "d:\My stuff\mypython\Tkinter\azan caller\azan_caller.py", line 152, in call_azan
playsound(azan_path)
File "C:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\playsound.py", line 17, in _playsoundWin
from random import random
ImportError: cannot import name 'random' from 'random' (d:\My stuff\mypython\Tkinter\azan caller\random.py)
Random.py is another file in the folder but I never used it in my main python file. This is my full code just for completeness:
import tkinter as tk
from tkinter import Grid
import xlrd
import os
from xlrd import cellname,xldate_as_tuple,xldate_as_datetime
from datetime import date
from datetime import datetime , timedelta
from playsound import playsound
from tkinter import font
#set time and current date
current_time = datetime.strftime(datetime.now(), "%I:%M %p") #time.strftime("%I:%M %p")
todays_date = date.today()
month = todays_date.strftime('%m')
def current_date(todays_date):
format_date = todays_date.strftime("%d/%m/%Y")
return format_date
format_date = current_date(todays_date)
#function to display current time
def display_time():
current_time = datetime.strftime(datetime.now(), "%I:%M %S %p")
lbl_display_time.config(text=current_time)
lbl_display_time.after(1000,display_time)
#function to display current date
def display_date():
todays_date = date.today()
month = todays_date.strftime('%m')
format_date = todays_date.strftime("%d/%m/%Y")
lbl_display_date.config(text=format_date)
lbl_display_date.after(1000,display_date)
#open workbook
filename = os.path.join("D:\My stuff\mypython\Tkinter",'azan caller\prayer_timings.xlsx')
workbook = xlrd.open_workbook(filename)
worksheet = workbook.sheet_by_name('Sheet %s'% month)
def get_date(format_date):
#number of rows in sheet
rows = worksheet.nrows
#get date from excel file and compare with current date
raw_date = ''
for i in range(-1,rows):
raw_date = worksheet.cell_value(i,1)
conv_date = datetime(*xlrd.xldate_as_tuple(raw_date, workbook.datemode))
excel_date = conv_date.strftime("%d/%m/%Y")
if format_date == excel_date:
cell_location = (i,1)
break
return [cell_location , excel_date]
def calc_countdown():
''' This function calculates the remaining time before the next prayer '''
#converts prayer times to datetime object
struc_prayertime_list = [datetime.strptime(i, "%I:%M %p") for i in azan_time]
#gets the current time and converts it to datetime object
current_time = datetime.strptime(datetime.strftime(datetime.now(), "%I:%M:%S %p"), "%I:%M:%S %p")
#gets the next prayer time
nearest_time = next((i for i in struc_prayertime_list if i > current_time), datetime.strptime('01-02 04:18 AM', "%m-%d %I:%M %p"))
#calculates the time left before next prayer, converts it to string and stores it in a variable
time_left_text.set("{} hours {} minutes {} seconds".format(*str(nearest_time - current_time).split(":")))
random_lbl.after(1000, calc_countdown)
#get time for different prayers
def fajr_time(cell_location):
fajr = worksheet.cell_value(cell_location[0][0],3)
return fajr
def zuhr_time(cell_location):
zuhr = worksheet.cell_value(cell_location[0][0],5)
return zuhr
def asr_time(cell_location):
asr = worksheet.cell_value(cell_location[0][0],6)
return asr
def maghrib_time(cell_location):
maghrib = worksheet.cell_value(cell_location[0][0],7)
return maghrib
def isha_time(cell_location):
isha = worksheet.cell_value(cell_location[0][0],8)
return isha
def update_time():
''' this function will run continuoulsy and its function is to keep updating the prayer times
as the day and date changes flow : get the correct cell_location using get_Date() --- set prayer times
using cell_location --- append prayer times(variables) to a list called azan_time--- return azan_time '''
cell_location = get_date(format_date)
#set prayer times
fajr = fajr_time(cell_location)
fajr="0"+fajr
zuhr = zuhr_time(cell_location)
asr = asr_time(cell_location)
maghrib = maghrib_time(cell_location)
isha = isha_time(cell_location)
#store prayer times in a list
azan_time = [fajr,zuhr,asr,maghrib,isha,"3:10 PM"]
#checks if any of the time is in PM. IF so, a '0' is added to the beginning
azan_time.remove(zuhr) #temporarily remove zuhr time
for x in range(0,len(azan_time)):
temp_time = azan_time[x]
if temp_time[-2]+temp_time[-1] == 'PM':
azan_time[x] = '0'+azan_time[x]
azan_time.insert(1,zuhr) # add zuhr time back
random_lbl.after(1000,update_time)
return azan_time #return azan time so it can be used
#function to check if it is time for prayer
def call_azan():
current_time = datetime.strftime(datetime.now(), "%I:%M %p")
for i in range(0,len(azan_time)):
if current_time == azan_time[i]:
print("time to pray at" , azan_time[i])
azan_path = os.path.join("azan caller","azan_sound.mp3")
playsound(azan_path)
else:
continue
random_lbl.after(1000,call_azan)
#GUI
window = tk.Tk()
window.title("Azan Caller")
Grid.rowconfigure(window, 0, weight=1)
Grid.columnconfigure(window, 0, weight=1)
#set up window
height = window.winfo_screenheight()
width = window.winfo_screenwidth()
window.geometry(f'{int(width/2)}x{int(height/2)}')
frm_window = tk.Frame(window,bg="#00BFFF")
frm_window.pack(fill="both",expand=True)
# a label just to run the functions continuously after 1 second
random_lbl = tk.Label(frm_window,width=2)
#create fonts
heading_font = font.Font(family = "ShareTech",size=25,weight='bold')
subheading_font = font.Font(family="ShareTech",size=14)
body_font = font.Font(family="ShareTech",size=10,weight="bold")
# title section
frm_title = tk.Frame(frm_window,relief=tk.SOLID,borderwidth=3,bg="#000000")
frm_title.grid(row=0, column=0, sticky="new",pady=(0,5))
lbl_title = tk.Label(master=frm_title, text="Azan Caller For Abu Dhabi",font=heading_font,fg="#008000")
lbl_title.pack(side='top',fill='x')
#prayer timings table
frm_table = tk.Frame(frm_window,bg="#000000",relief=tk.SOLID,borderwidth=3)
frm_table.grid(row=1,column=0, sticky="nsew",padx=(20,20))
tbl_title = tk.Label(frm_table,text="Today's Prayer Times",relief=tk.SOLID,font=subheading_font,borderwidth=2)
tbl_title.grid(row=0,column=0,columnspan=5,sticky="nsew")
#prayer names
prayer_names = ['Fajr','Zuhr','Asr','Maghrib','Isha']
for j in range(0,len(prayer_names)):
name = prayer_names[j]
cell = tk.Label(frm_table,text=name,relief=tk.SOLID,font=body_font,borderwidth=2)
cell.grid(row=1,column=j,sticky="nsew")
#prayer times
azan_time = update_time()
for i in range(0,len(azan_time)):
prayer_time = azan_time[i]
cell_time = tk.Label(frm_table,text=prayer_time,relief=tk.SOLID,font=body_font,borderwidth=2,fg="#FF8C00")
cell_time.grid(row=2,column=i,sticky="nsew")
#body section
frm_body = tk.Frame(frm_window,relief=tk.SOLID,borderwidth=5,)
frm_body.grid(row=2, column=0, sticky="nsew",pady=(10,10),padx=(20,20))
lbl_date = tk.Label(frm_body,text="Today's Date: ",font=body_font)
lbl_date.grid(row=0,column=0,sticky="nsew",pady=(0,5))
lbl_display_date = tk.Label(frm_body,font=body_font)
lbl_display_date.grid(row=0,column=1,sticky="nsew",pady=(0,5))
lbl_time = tk.Label(frm_body,text="Current Time: ",font=body_font)
lbl_time.grid(row=1,column=0,sticky="nsew",pady=(0,5))
lbl_display_time = tk.Label(frm_body,font=body_font)
lbl_display_time.grid(row=1,column=1,sticky="nsew",pady=(0,5))
time_left_text = tk.StringVar()
lbl_countdown = tk.Label(frm_body,text="Next Prayer in : ",font=body_font)
lbl_countdown.grid(row=2,column=0,sticky="nsew",pady=(0,5))
lbl_display_countdown = tk.Label(frm_body,textvariable=time_left_text,font=body_font,fg="red")
lbl_display_countdown.grid(row=2,column=1,sticky="nsew",pady=(0,5))
#footer
frm_footer = tk.Frame(frm_window,relief=tk.SOLID,borderwidth=3,bg="#000000")
frm_footer.grid(row=3, column=0, sticky="sew",pady=(10,0))
lbl_footer = tk.Label(frm_footer,text="#Copyright AbdulRahman Tijani 2020",font=body_font,fg="#008000")
lbl_footer.pack(side="bottom",fill='x')
#make the structure resizable
#columns
for i in range(frm_window.grid_size()[0]):
frm_window.grid_columnconfigure(i, weight=1)
for i in range(frm_table.grid_size()[0]):
frm_table.grid_columnconfigure(i, weight=1)
for i in range(frm_body.grid_size()[0]):
frm_body.grid_columnconfigure(i,weight=1)
#row
for i in range(frm_window.grid_size()[1]):
frm_window.grid_rowconfigure(i, weight=1)
for i in range(frm_table.grid_size()[1]):
frm_table.grid_rowconfigure(i, weight=1)
for i in range(frm_body.grid_size()[1]):
frm_body.grid_rowconfigure(i,weight=1)
#run functions
display_date()
display_time()
update_time()
call_azan()
calc_countdown()
window.mainloop()
Thank you in Advance
The problem here is because you have a file in your directory called random.py which is being imported here and python is reading that in and not the random module, so try not to name your script files as same as the module names.
And instead of using playsound, why dont you try the pygame module for playing sounds. Refer how to here
I'm looking for a way to count each day passed from a start date in python. So if the start date was 21/02/2020 and count equals to 0, when the next day starts count should increment by 1.
Edit: After using Rusty's code I am able to show you a minimal reproducible example.
import datetime
start = datetime.datetime.strptime(input("Choose a start date (mm/dd/yyyy): "), '%m/%d/%Y')
current = datetime.datetime.now()
delta = current - start
count = delta.days
print(count)
import datetime
import time
count = 0
# "...from today..."
today = datetime.datetime.today()
# "...to infinity..."
while True:
now = datetime.datetime.today()
# "...as soon as the next day starts..."
if today.day != now.day:
# "...it would increment count by 1..."
count = count + 1
print(count)
today = now
time.sleep(1)
import datetime
today = datetime.datetime.strptime('03/21/2020', '%m/%d/%Y')
tomorrow = datetime.datetime.strptime('03/22/2020', '%m/%d/%Y')
next_saturday = datetime.datetime.strptime('03/28/2020', '%m/%d/%Y')
delta = tomorrow - today
count = delta.days
print(count)
delta = next_saturday - today
count = delta.days
print(count)
So I can generate random days in a given start-end date relationship, but, if the date happens to be a weekend - currently all I can get working is to print to the user 'it is a weekend'. What I would like to do is, if the random day IS a weekend, rerun the function so the user does not have to manually. Basically - only print out weekdays - currently, if the random day is a weekend, it prints a blank space or None value. Only return/print weekdays is the main goal.
Here is the code so far:
from datetime import datetime, timedelta
from random import randrange
def random_date(start, end):
delta = end - start
random_day = randrange(delta.days)
myresult = start + timedelta(days=random_day)
return myresult
d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
myresult = random_date(d1, d2)
if myresult.weekday() not in (5, 6):
print myresult.strftime('%m-%d-%Y')
else:
print "hit a weekend"
An option:
def random_weekday(start, end):
date = None
while (not date or date.weekday() in (5, 6)):
days = randrange((end - start).days)
date = start + timedelta(days=days)
return date
start = datetime.strptime('9/1/2018', '%m/%d/%Y')
end = datetime.strptime('9/30/2018', '%m/%d/%Y')
for i in range(20):
print(random_weekday(start, end).strftime('%m-%d-%Y'))
So, you need a while-loop to keep getting dates until you get one that's not a weekend, like this:
from datetime import datetime
from random import randrange
from datetime import timedelta
def random_date(start, end):
delta = end - start
random_day = randrange(delta.days)
myresult = start + timedelta(days=random_day)
return myresult
while True:
d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
myresult = random_date(d1, d2)
if myresult.weekday() not in (5,6):
break
print myresult.strftime('%m-%d-%Y')