每小时在Python中写入时间戳到文件

3 投票
1 回答
6938 浏览
提问于 2025-04-15 18:55

我有一个Python脚本,它一直在从Twitter上抓取数据,并把这些消息写入一个文件。我的问题是,每小时我想让我的程序在文件中写入当前的时间。下面是我的脚本。目前,它进入时间戳函数后,每10秒就打印一次时间。

#! /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()

有没有办法让我的脚本在不每分钟都用IF语句检查时间的情况下实现这个功能?我能否像我上面做的那样,稍微修改一下当前的实现,使用定时任务?

1 个回答

4

你的代码

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秒就行了。

撰写回答