Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中每小时向文件写入时间戳_Python_File Io - Fatal编程技术网

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

在Python中每小时向文件写入时间戳,python,file-io,Python,File Io,我有一个python脚本,它不断地从Twitter获取数据,并将消息写入文件。我的问题是每小时,我希望我的程序将当前时间写入文件。下面是我的脚本。目前,它进入了timestamp函数,只是每10秒打印一次时间 #! /usr/bin/env python import tweetstream import simplejson import urllib import time import datetime import sched class twit: def __init__

我有一个python脚本,它不断地从Twitter获取数据,并将消息写入文件。我的问题是每小时,我希望我的程序将当前时间写入文件。下面是我的脚本。目前,它进入了timestamp函数,只是每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语句每隔一分钟检查一次时间的情况下执行此操作?我可以像上面那样使用一个计划任务,对当前实现稍加修改吗?

您的代码

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秒