【问题标题】:Comparing Time - Python [duplicate]比较时间 - Python [重复]
【发布时间】:2019-05-20 00:36:01
【问题描述】:

我有一个函数可以从文件中读取时间。我把它放到一个变量中。然后我从当前时间中减去这个值,大部分时间会给我一个大约 .

我的问题是我不确定如何检查我附加到变量的这个值是否大于 20 秒。

def numberchecker():
    with open('timelog.txt', 'r') as myfile:
        data=myfile.read().replace('\n','')

    a = datetime.strptime(data,'%Y-%m-%d %H:%M:%S.%f')
    b = datetime.now()
    c = b-a   (This outputs for example: 0:00:16.657538)

    d = (would like this to a number I set for example 25 seconds)


    if c > d:
        print ("blah blah")

【问题讨论】:

    标签: python datetime variables math


    【解决方案1】:

    你得到的区别是一个timedelta 对象。

    您可以使用c.seconds 来获取秒数。

    【讨论】:

    • 添加了对错误答案的评论。我这样做了,但仍然出错
    • 使用c.seconds > d 而不仅仅是c > d
    【解决方案2】:
    if c.total_seconds() > datetime.timedelta(seconds=d):
        print ("blah blah")
    

    【讨论】:

    • 当我将一个 int 分配给 d(例如 10)时,我得到错误 TypeError: unorderable types: datetime.timedelta() > int()
    • 将 d 转换为时间增量:datetime.timedelta(seconds=d)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多