简体   繁体   English

如何使用python找时间?

[英]how to find time using python?

i want to run my function and then I want to find now's time using python. 我想运行我的函数,然后我想使用python查找现在的时间。

then lets say after 2 hours my function should run again. 然后说2小时后,我的功能应该再次运行。

what should i do? 我该怎么办?

There are several ways of finding the time in Python: 有几种方法可以在Python中找到时间:

import time
print time.time() # unix timestamp, seconds from 1970

import datetime
print datetime.datetime.now()

time.sleep(7200) # sleep for 2 hours

to determine current time, you can use pythons datetime module 确定当前时间,可以使用pythons datetime模块

from datetime import datetime
print datetime.datetime.now();

To run script every two hours - this is a job to crontab deamon. 每两个小时运行一次脚本-这是crontab守护进程的工作。 This is a special process in UNIX systems that executed commands in periods of time. 这是在一段时间内执行命令的UNIX系统中的一个特殊过程。

Read about setting up cron jobs here: http://blog.dreamhosters.com/kbase/index.cgi?area=2506 在此处阅读有关设置cron作业的信息: http : //blog.dreamhosters.com/kbase/index.cgi?area=2506

import datetime
import time

def func():
    # your function
    pass


while True:
    func() # call you function
    print datetime.datetime.now() # print current datetime
    time.sleep(2*60*60) # sleep for 2 hours

However, a better way for a scheduled operation would be to use cron , as @Silver Light suggested. 但是,如@Silver Light建议的那样,计划操作的更好方法是使用cron

Is your process going to be running for hours at a time and doing other things? 您的流程一次要运行几个小时并执行其他操作吗? If so you can mark the time like so: 如果是这样,您可以这样标记时间:

from time import time

start_time = time()   # current time expressed as seconds since 1/1/1970

...

now = time()
if (now - start_time) >= (2 * 60 * 60):   # number of seconds in 2 hours
  do_function()

Otherwise, if it will not need to do anything for 2 hours, you can do: 否则,如果2小时内无需执行任何操作,则可以执行以下操作:

from time import sleep

quit_condition = False

if not quit_condition:
  sleep(2 * 60 * 60)     # control will not return to this thread for 2 hours
  quit_condition = do_function()

In the second scenario, presumably your function will indicate whether or not the main loop can be exited. 在第二种情况下,大概您的函数将指示是否可以退出主循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM