我正在尝试构建一个脚本,该脚本在2小时之间选择一个随机时间,当所选的随机时间到来时,它将播放一首歌曲。
在我编写的脚本中,每次运行时,它都会显示当前时间和另一个随机时间。如果我不久之后再次运行它,它将随机选择一个小时。我想弄清楚如何运行脚本,以便随机时间每天只选择一次,而当前时间每秒钟更新一次。当当前时间和随机时间相等时,将播放歌曲。
import datetime
from random import randrange
from datetime import timedelta
from pygame import mixer
blank = ' '
# find the current time
now = datetime.datetime.now()
date_today = now.strftime('%m/%d/%Y')
time_now = now.strftime('%T')
time_now_newFormat = now.strftime('%Y-%m-%d %T')
print(f"now is {time_now_newFormat}")
# choose random time between 2 to 4
def random_date(start, end):
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
return start + timedelta(seconds=random_second)
from datetime import datetime
h1 = date_today + " " + "2:00 PM"
h2 = date_today + " " + "4:00 PM"
hour1 = datetime.strptime(h1, '%m/%d/%Y %I:%M %p')
hour2 = datetime.strptime(h2, '%m/%d/%Y %I:%M %p')
ran = random_date(hour1, hour2)
print(f"your random time is {ran}")
#store the random time in a file
file_time = open('file_time.txt', 'w')
print(file_time)
line1 = ran
file_time.write(str(line1))
file_time.close()
#open the file and compare times
fhand = open("file_time.txt")
for line in fhand:
if line == time_now_newFormat:
mixer.init()
mixer.music.load(r"C:\Users\BLACK 8\Desktop\Personal\Python\Alarm.mp3")
mixer.music.play()