Writing a timestamp to a file every hour in Python

I have a python script that constantly captures data from Twitter and writes messages to a file. The question I have is every hour, I want my program to write the current time to a file. Below is my script. Currently, it falls into the timestamp function and just keeps printing time every 10 seconds.

#! /usr/bin/env python
import tweetstream
import simplejson
import urllib
import time
import datetime
import sched

class twit: 
    def __init__(self,uname,pswd,filepath):
        self.uname=uname
        self.password=pswd
        self.filepath=open(filepath,"wb")

    def main(self):
        i=0
        s = sched.scheduler(time.time, time.sleep)
        output=self.filepath

        #Grab every tweet using Streaming API
        with tweetstream.TweetStream(self.uname, self.password) as stream:
            for tweet in stream:
                if tweet.has_key("text"):
                    try:
                        #Write tweet to file and print it to STDOUT
                        message=tweet['text']+ "\n"
                        output.write(message)
                        print tweet['user']['screen_name'] + ": " + tweet['text'], "\n"

                        ################################
                        #Timestamp code
                        #Timestamps should be placed once every hour
                        s.enter(10, 1, t.timestamp, (s,))
                        s.run()
                    except KeyError:
                        pass
    def timestamp(self,sc):
        now = datetime.datetime.now()
        current_time= now.strftime("%Y-%m-%d %H:%M")
        print current_time
        self.filepath.write(current_time+"\n")


if __name__=='__main__':
    t=twit("rohanbk","cookie","tweets.txt")
    t.main()

Anyway, for my script to do this without checking the time every minute with the IF statement to find out how much time has passed? Can I use a scheduled task, for example, as it was done above, with a slight modification of my current implementation?

+3
source share
1 answer

your code

sc.enter(10, 1, t.timestamp, (sc,)

10 . ,

sc.enter(3600, 1, t.timestamp, (sc,)

, 3600 , 10!

,

s.enter(1, 1, t.timestamp, (s,))

1 - ? , , 10 3600.

+4

Source: https://habr.com/ru/post/1731494/


All Articles