【问题标题】:Inputting the time and comparing it with user input输入时间并将其与用户输入进行比较
【发布时间】:2011-08-12 11:36:33
【问题描述】:

我试图让一个函数在用户给定的某个时间在 Python 脚本中运行。为此,我使用了 datetime 模块。

这是目前为止的部分代码:

import os
import subprocess
import shutil
import datetime
import time

def process():

    path = os.getcwd()
    outdir = os.getcwd() + '\Output'

    if not os.path.exists(outdir):
        os.mkdir(outdir, 0777)

    for (root, dirs, files) in os.walk(path):
        filesArr = []
        dirname = os.path.basename(root)
        parent_dir = os.path.basename(path)

        if parent_dir == dirname:
            outfile = os.path.join(outdir,  ' ' + dirname + '.pdf')
        else:
            outfile = os.path.join(outdir, parent_dir + ' ' + dirname + '.pdf')

        print " "
        print 'Processing: ' + path

        for filename in files:
            if root == outdir:
                continue
            if filename.endswith('.pdf'):
                full_name = os.path.join(root, filename)
                if full_name != outfile:
                    filesArr.append('"' + full_name + '"')

        if filesArr:
            cmd = 'pdftk ' + ' '.join(filesArr) + ' cat output "' + outfile + '"'
            print " "
            print 'Merging: ' + str(filesArr)

            print " "

            sp = subprocess.Popen(cmd)

            print "Finished merging documents successfully."

            sp.wait()

    return

now = datetime.datetime.now()
hour = str(now.hour)
minute = str(now.minute)
seconds = str(now.second)
time_1 = hour + ":" + minute + ":" + seconds

print "Current time is: "  + time_1

while True:
     time_input = raw_input("Please enter the time in HH:MM:SS format: ")

     try:
        selected_time = time.strptime(time_input, "%H:%M:%S")
        print "Time selected: " + str(selected_time)

        while True:
            if (selected_time == time.localtime()):
             print "Beginning merging process..."
             process()
             break
             time.sleep(5)

        break

     except ValueError:
        print "The time you entered is incorrect. Try again."

问题是试图找到一种方法来比较用户输入的时间与当前时间(例如,脚本运行时的当前时间)。另外,如何让 python 脚本在给定时间运行并处理函数?

【问题讨论】:

    标签: python datetime time input compare


    【解决方案1】:

    我可以在您提出的代码中看到各种需要注释的内容,但主要的是 selected_time = selected_hour + ...,因为我认为您正在添加具有不同单位的整数。你应该从selected_time = selected_hour * 3600 + ...开始。

    第二个是当您尝试检查输入的有效性时:您在无法进化的检查上进行while,因为不要求用户输入另一个值。这意味着这些循环永远不会结束。

    然后,关于健壮性:也许您应该通过更灵活的方式将所选时间与当前时间进行比较,即将== 替换为>= 或一些增量。

    最后,您可以使用以下命令让 Python 脚本等待:

    import time
    time.sleep(some_duration)
    

    some_duration 是一个浮点数,以秒为单位。

    请您检查一下现在是否有效?

    【讨论】:

    • 我更新了代码并按照你告诉我的做了,还使用了@alexandru Plugaru 的代码建议,但是,它没有正确输出时间 process() doesn't run
    • 您在比较timeselected_time 接近尾声时错过了比较变化。您需要做的是与 delta 进行比较:if selected_time >= current_time >= selected_time + delta 否则您可能会绕过您的预定时间。第二点,time 比较的是模块,而不是当前时间,所以你的比较永远不会起作用!
    • @Brian,我在这里回答,因为我无法回答您向 Alexandru 提出的问题。您遇到的问题是您希望 selected_time 与当前时间相等。这不太可能发生,因为您的等待时间为 5 秒。在您的比较中,您应该在expected_time 周围留出一些余量(请参阅我上面的评论)。
    【解决方案2】:

    首先我建议你看看:http://docs.python.org/library/time.html#time.strptime 在尝试验证时间时,这可能对您的情况有所帮助。

    你可以这样: 进口时间

    import time
    
    while True: #Infinite loop        
        time_input = raw_input("Please enter the time in HH:MM:SS format: ")
        try:
            current_date = time.strftime("%Y %m %d")
            my_time = time.strptime("%s %s" % (current_date, time_input),
                                 "%Y %m %d  %H:%M:%S")
            break #this will stop the loop
        except ValueError:
            print "The time you entered is incorrect. Try again."
    

    现在你可以用my_time 做一些事情,比如比较它:my_time == time.localtime()

    让程序运行到“时间到了”的最简单方法如下:

    import time
    
    while True:
        if (my_time <= time.localtime()):
            print "Running process"
            process()
            break
        time.sleep(1) #Sleep for 1 second
    

    上面的例子绝不是最好的解决方案,但在我看来是最容易实现的。

    另外我建议你尽可能使用http://docs.python.org/library/subprocess.html#subprocess.check_call 来执行命令。

    【讨论】:

    • 我在尝试您的代码时收到此错误:AttributeError: 'str' object has no attribute 'strptime'
    • 好的,问题是我有一个名为 time 的变量。我改变了它。我更新了主要问题中的代码。尽管它没有正确输出时间并且进程没有运行,但它仍然可以正常工作。
    • 问题出在:if (selected_time == time): 您正在将selected_time 变量(它是一个time.struct_time 对象)与模块time 进行比较。相反,您应该这样做 if (selected_time == time.localtime()) 我应该更好地编写示例。
    • 我再次更新了代码(在主要问题中).. 没有任何反应.. 程序一直在等待。有什么帮助吗?
    • 试试这个:pastie.org/2379400 - 如您所见,我添加了current_date = time.strftime("%Y %m %d"),以便我们可以与time.localtime() 进行比较,否则我们比较1900 年的日期,该日期总是小于2011 年的日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多