Python Forum
Help adding a loop inside a loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help adding a loop inside a loop
#21
You have two loops that read events from the database. One to get the reminder message and one to get the reminder time. You should GET the reminders message and scheduled times at the same time, just like I did in my example. One loop, not two.

Using two loops is messing you up. First you get all your times, then you schedule your reminders. Because of this you schedule all your events to use the same time. The last time retrieved from the database.

Why are you doing this?
    #Convert scheduled_time from Tuple to List
    from itertools import chain
    DateTimeList = list(chain.from_iterable(scheduled_time))
    #Then Convert the List to a String
    DateTimeStr = "".join(str(x) for x in DateTimeList)
Do you understand any of that code? This is the most convoluted scheme I've ever seen to get a value from a tuple.

I don't understand your confusion about tuples. A tuple is just like a list, except it is immutable. If you want to get the value from the tuple, use indexing (scheduled_time[0]) or unpacking (*scheduled_time), just like you would do to get values from a list. When you fix your program to retrieve the reminder message and scheduled time together with a single query, unpacking will be the best choice.
    for message, sched_time in db.execute("SELECT Reminder, DateTime FROM Reminders"):
        schedule_reminder(message, sched_time)
I no longer think Datetime is the right type for saving schedule time in the database. You need timestamps for scheduling and sqlite allows saving timestamps in their native format, unlike DateTime that must be converted to/from a string. Using timestamps for the schedule time also makes it possible to use queries to delete old reminders, or only retrieve reminders that occur during a specific time span. That would be a nice feature if you want to display a calendar of events. The only disadvantage of timestamps is they are not human readable. To input a schedule time you'll need to convert a string to a timestamp (strptime() to convert string to DateTime, timestamp() to convert DateTime to timestamp(). To display a schedule time you'll need to convert a timestamp to a string (.fromtimestamp() to convert timestamp to DateTime, strftime() to convert DateTime to string).
import sqlite3 as sql
from datetime import datetime
import sched, time
 
time_format = "%I:%M %p"
 
def send_reminder(sched_time, message):
    """Print time> Message and scheduled time"""
    sched_time = datetime.fromtimestamp(sched_time).strftime(time_format)
    now = datetime.now().strftime(time_format)
    print(f"{now}> {message}\nScheduled: {sched_time}\n")

def enter_reminders():
    """Generate a list of reminders.  End by entering a blank message"""
    while True:
        reminder = input("Message: ")
        if not reminder:
            break
        sched_time = datetime.strptime(input("HH:MM AM/PM: "), time_format)
        sched_time = datetime.now().replace(
            hour=sched_time.hour,
            minute=sched_time.minute,
            second=0)
        yield sched_time.timestamp(), reminder


def save_reminders(reminders):
    """Make a table in the database to hold the reminders
    Table reminders
    Time a timestamp, Reminder a string
    """
    db = sql.connect("test.db")
    db.execute("CREATE TABLE IF NOT EXISTS reminders(Time INTEGER, Reminder TEXT)")
    db.execute("DELETE FROM reminders")  # For demonstration purposes only
    for reminder in reminders:
        db.execute(
            "INSERT INTO reminders (Time, Reminder) VALUES(?, ?)", reminder)
    db.commit()
    db.close()
 
def schedule_reminders(schedule):
    """Get reminders from the database and add to the schedule."""
    db = sql.connect("test.db")
    for sched_time, reminder in db.execute("SELECT Time, Reminder FROM reminders"):
        schedule.enterabs(sched_time, 1, send_reminder, (sched_time, reminder))
    db.close()

print("Enter reminders")
save_reminders(enter_reminders())

print("\nScheduling reminders:")
schedule = sched.scheduler(time.time)
schedule_reminders(schedule)

print("\nPlay reminders.")
while not schedule.empty():
    schedule.run()
Reply


Messages In This Thread
Help adding a loop inside a loop - by Extra - Oct-09-2022, 09:37 PM
RE: Help adding a loop inside a loop - by Extra - Oct-09-2022, 10:41 PM
RE: Help adding a loop inside a loop - by Extra - Oct-10-2022, 02:36 PM
RE: Help adding a loop inside a loop - by Extra - Oct-10-2022, 03:01 PM
RE: Help adding a loop inside a loop - by Extra - Oct-10-2022, 05:07 PM
RE: Help adding a loop inside a loop - by Extra - Oct-10-2022, 06:38 PM
RE: Help adding a loop inside a loop - by Extra - Oct-10-2022, 07:31 PM
RE: Help adding a loop inside a loop - by Extra - Oct-15-2022, 03:52 PM
RE: Help adding a loop inside a loop - by Extra - Oct-15-2022, 07:10 PM
RE: Help adding a loop inside a loop - by Extra - Oct-15-2022, 11:12 PM
RE: Help adding a loop inside a loop - by Extra - Oct-16-2022, 12:17 AM
RE: Help adding a loop inside a loop - by deanhystad - Oct-16-2022, 04:50 PM
RE: Help adding a loop inside a loop - by Extra - Oct-16-2022, 06:10 PM
RE: Help adding a loop inside a loop - by Extra - Oct-17-2022, 10:41 PM
RE: Help adding a loop inside a loop - by Extra - Oct-17-2022, 11:23 PM
RE: Help adding a loop inside a loop - by Extra - Oct-19-2022, 01:01 AM
RE: Help adding a loop inside a loop - by Extra - Oct-23-2022, 12:16 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help with a while loop ampereap 4 186 May-31-2024, 02:25 PM
Last Post: ampereap
  problem program runs in a loop jasserin 0 184 May-18-2024, 03:07 PM
Last Post: jasserin
  [SOLVED] Loop through directories and files one level down? Winfried 3 411 Apr-28-2024, 02:31 PM
Last Post: Gribouillis
  Loop through all files in a directory? Winfried 10 773 Apr-23-2024, 07:38 PM
Last Post: FortuneCoins
  for loop not executing Abendrot47 2 349 Apr-09-2024, 07:14 PM
Last Post: deanhystad
  Re Try loop for "net use..." failures tester_V 10 805 Mar-02-2024, 08:15 AM
Last Post: tester_V
  File loop curiously skipping files - FIXED mbk34 10 1,061 Feb-10-2024, 07:08 AM
Last Post: buran
  Optimise multiply for loop in Python KenBCN 4 595 Feb-06-2024, 06:48 PM
Last Post: Gribouillis
  Basic binary search algorithm - using a while loop Drone4four 1 483 Jan-22-2024, 06:34 PM
Last Post: deanhystad
  loop through csv format from weburl in python maddyad82 3 540 Jan-17-2024, 10:08 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020