python用时间戳给文件命名-在Python中每小时将时间戳记写入文件

我有一个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"]+ " "

output.write(message)

print tweet["user"]["screen_name"] + ": " + tweet["text"], " "

################################

#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+" ")

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.

标签:file-io,python

来源: https://codeday.me/bug/20191106/2001452.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值