Cedric
Cedric

Reputation: 152

Converting str into datetime and fetching all data from db

I tried to make a tasks.loop() for checking a muted user that needs to be unmuted, but there's a few problem while doing this, i can't use fetchall() for some reason because it will gives me this error

toremove = muteremove[2]
IndexError: list index out of range

If i use fetchone() maybe it only fetch 1 user every 10 secs, i mean how to fetch all the data every 10 sec to unmute a user? Also if i use fetchone() it will say that it can't convert str into datetime.datetime object, how can i fix this?

    @tasks.loop(seconds=10)
    async def muted_user_check(self):
        self.cur.execute(f"SELECT userId, guildId, expiredAt FROM mutedlist")
        muteremove = self.cur.fetchall()
        if muteremove is None:
            print("No user to unmute :D")
        if muteremove is not None:
            toremove = muteremove[2]
            timenow = datetime.utcnow()
            if timenow > toremove:
                self.cur.execute(f"DELETE FROM mutedlist WHERE guildId = {muteremove[1]} and userId = {muteremove[0]}")

Upvotes: 0

Views: 58

Answers (1)

MrSpaar
MrSpaar

Reputation: 3994

To convert a string into a datetime object, you can use the strptime() method:

from datetime import datetime

def convert(date, format):
    return datetime.strptime(date, format)

[input] convert('22/08/2020', '%d/%m/%Y')
[output] 2020-08-22 00:00:00

The output will be a datetime object that you can format with the strftime() method like so:

#Example
from datetime import datetime

now = datetime.now() #now will be a datetime object
now.strftime('%d/%m/%Y - %H:%M:%S') # DD/MM/YYYY - hours:minutes:seconds

Here's a list of some formats:

  • %A → Weekday (%a for abreviations and %w for numbers)
  • %-d → day of the mount (1, 2, 3, 4, ...)
  • %B → Mounth name (%b for abreviations and %-m for numbers)
  • %I → Hour (12h clock)
  • %p → AM or PM
  • %H → Hour (24h clock)
  • %M → Minutes
  • %S → Seconds
  • %f → Microseconds
  • %c → Local date and time representation

Using your code, it would be:

@tasks.loop(seconds=10)
async def muted_user_check(self):
    self.cur.execute(f"SELECT * FROM mutedlist")
    mute_list = self.cur.fetchall()
    if not mute_list:
        print("No user to unmute :D")
    else:
        timeNow = datetime.utcnow()
        for mute in mute_list:
            muteExpire = datetime.strptime(mute[3], '%Y-%m-%d %H:%M:%S')
            if timeNow > muteExpire :
                self.cur.execute(f"DELETE FROM mutedlist WHERE guildId=? AND userId=?", (mute[0], mute[1]))

Upvotes: 1

Related Questions