[Solved] I am trying to get my python twitter bot to tweet every 30 minutes on the hour. What should I do? [closed]


So using datetime you can actually get the minutes like this:

from datetime import datetime

time = datetime.now()

minutes = time.minute

Or in one line:

from datetime import datetime

minutes = datetime.now().minute

Now that you have the minutes, the if statement can be simplified down, because you don’t look at the hour.

if minutes == 0 or minutes == 30:
    # do tweet

EDIT:

You commented asking:
“Also curious, does that mean I need to run my program on the hour of :00 because the time is created through the now function?”

So theoretically here there are a few ways to answer this. Firts wrap your code in a function and call it constantly:

def tweet_check(minutes):
    minutes = datetime.now().minutes

    if minutes == 0 or minutes == 30:
        # do tweet

if __name__ == '__main__':
    # This would be how it constantly runs the check
    while true:
        tweet_check()

Option 1:

Then you can just manually run the script when ever you want your bot to be tweeting every 30 minutes.

Option 2

With the check if main == ‘main‘ you will be able to import this script to another one and then run it on your own terms. As an imported script you can go the route of using the scheduler to run it at specific times.

Option 3:

Run it as a system scheduled task (windows) or a cron job (linux) to have it run on boot.

However it’s key to point out that if you do use it as option 2 or 3, it’s probably best to modify it where you can pass in an optional variable if you want it to just send no matter the time.

So I would modify it like so:

def tweet_check(time_check=True):
    if time_check:
        minutes = datetime.now().minutes

        if minutes == 0 or minutes == 30:
            # do tweet

    else:
        # do tweet

This is because option 2 and 3 both inherently have timing built into them. So it would be excessive/inefficient to do it again here. In this simple example, that won’t make much of a difference, but at the scale of say a few thousand tweets, that would end up rolling into the next minute and then would cut off some of the tweets.

5

solved I am trying to get my python twitter bot to tweet every 30 minutes on the hour. What should I do? [closed]