【问题标题】:Subtracting datetime's in Python在 Python 中减去日期时间
【发布时间】:2019-04-05 01:41:43
【问题描述】:

所以我正在尝试实现一个计时程序,我需要返回秒数(secs),以便我的计时程序启动我的灯。我研究的原始代码让我走得很远:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

唯一的问题是我将 x.replace 作为用户输入变量,现在我收到错误“TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'”

我理解这是因为您不能直接减去两个 datetime.datetime.time() 但我不确定如何将它们转换为我可以操作的东西。到目前为止,这是我的代码

import datetime
from threading import Timer
import tkinter as tk
import time

# =============================================================================
# userInput takes a formatted input and passes it back to main.
# =============================================================================
def userInput():
        try:
            a = datetime.datetime.strptime(input('When would you like to routine to start in HH:MM 24 hour format: '), "%H:%M").time()
            print (a.strftime("%H:%M"))
        except:
            print ("Please enter correct time in HHMM format")
        return a

# =============================================================================
# timeComparator is a function which, if the user changes any settings or chooses
# start in the middle of a cycle, implements the correct routine depending on where
# in the cycle it's in.
# =============================================================================            
def timeComparator(a):
    now = datetime.datetime.now().time()
    #this obtains the current time
    #if statement compares input from 
    print("the time now is: ", now)
    if (now < a):
        print ("hello human")
    elif (now > a):
        print ("hello plant")

# =============================================================================
# This routine is hard coded and cannot be changed by the user. It assumes that 
# there will be a total of 12 hours of light with the last hour, in other words
# the last 8% of light, shifting from a natural blue hue to a more red hue. 
# The auto routine will start at 8am and end at 8pm. By ending, the routine 
# stops light shifting and finally at 830PM, the lights turn off.
# NOTE NOTE NOTE NOTE NOTE
# This is NOT the actual light routine. This is JUST function that records
# the time and returns the seconds that begins the start command for the lights
# =============================================================================
def autoRoutine(a):
    now = datetime.datetime.now().time()
    #this is the start of the auto routine
    start=a
    delta_t = start-now

    secs = delta_t.seconds+1
    return secs

def blueFade():
    print("the lights are starting")
# =============================================================================
# Main function. Will be used to call all other functions
# =============================================================================
if __name__=="__main__":

    a = userInput()

    timeComparator(a)

    secs = autoRoutine(a)
    lights = Timer(secs, blueFade)
    lights.start()

所以说到底,我无法操作代码行

    delta_t = start-now

因此我无法启动lights.start() 函数。我曾尝试使用 time.strptime 进行比较,但我并没有像 time.mktime() 那样成功

【问题讨论】:

    标签: python datetime operands


    【解决方案1】:

    要从now() 确定以秒为单位的增量以及从小时和分钟构建的时间,我们可以使用time.hourtime.minutetime.second 属性。

    问题代码中的问题是它试图对两个 datetime.time 对象进行减法

    def autoRoutine(a):
        now = datetime.datetime.now().time()
        #this is the start of the auto routine
        start=a
        delta_t = start-now
    
        secs = delta_t.seconds+1
        return secs
    

    这会产生:

      File "<ipython-input-18-98011edfef89>", line 65, in autoRoutine
        delta_t = start-now
    
    TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
    

    为了更正,我们可以将datetime.time 转换为秒。见convert-datetime-time-to-seconds

    将此答案应用于您的问题:

    def autoRoutine(a):
        now = datetime.datetime.now().time()
        startSeconds = ((a.hour * 60) + a.minute) * 60
        nowSeconds = (((now.hour * 60) + now.minute) * 60) + now.second
        startSeconds - nowSeconds
    

    【讨论】:

    • 查理,我现在正在实施这个。我确实有一些问题。在第一个代码示例中,我可以按原样运行它,这很好。为什么这与我的代码中的不同?另外,我仍然需要在您的最后一个 sn-p 中添加一行,对吗? ``` secs = startSeconds-nowSeconds ```
    • 就您的问题而言,“我仍然需要 sec = ...”,答案是您不必拥有 secs。返回 python 函数的最后一个表达式。
    • 关于“为什么不同”,我明天必须看看。我今晚不在电脑旁。
    • 我不知道 Python 谢谢!此外,一切正常。对此,我真的非常感激。我正在拔头发!
    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 2022-01-10
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多