【问题标题】:Calculate time span in Python在 Python 中计算时间跨度
【发布时间】:2016-05-22 23:16:15
【问题描述】:

我在 Windows 64 位上使用 Python v2.x

我想实时记录两个时刻并计算时间跨度。 代码如下:

current_time1 = datetime.datetime.now().time() # first moment

# ... some statement...some loops...take some time...

current_time2 = datetime.datetime.now().time() # second moment

time_span = current_time1 - current_time2

显然最后一行是不可执行的,因为 current_time 不是整数,所以我的问题是,如何将此语句转换为整数来进行数学运算?转换为秒是我的第一个想法......

【问题讨论】:

标签: python datetime


【解决方案1】:

从另一个中减去一个datetime.datetime.now() 会得到一个datetime.timedelta 实例。如果你在上面运行dir(),你可能会发现一些有用的功能。

>>> x = datetime.datetime.now()
# wait a second or two or use time.sleep()
>>> y = datetime.datetime.now()
>>> z = y - x
>>> type(z)
<type 'datetime.timedelta'>
>>> print(list(filter(lambda x: not x.startswith("_"), dir(z))))
['days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']
>>> print(z.total_seconds())
2.31

【讨论】:

    【解决方案2】:
    current_time1 = datetime.datetime.now()
    time.sleep(50)
    current_time2 = datetime.datetime.now()
    
    print (current_time2 - current_time1)
    

    或者

    time1 = time.time()
    time.sleep(50)
    time2 = time.time()
    print("%s seconds"%(time2-time1))
    

    【讨论】:

    • 糟糕,出现错误:TypeError: unsupported operand type(s) for -: 'datetime.time' and datetime.time
    • 我的回答中没有datetime.time...你显然没有复制粘贴它...
    【解决方案3】:
    import time
    
    current_time1 = time.clock()
    do_something()
    current_time2 = time.clock()
    print "%.2gs" % (current_time2-current_time1)
    

    编辑:

    from datetime import datetime, date
    
    datetime.combine(date.today(), current_time2) - datetime.combine(date.today(), current_time1)
    

    【讨论】:

    • 哎呀,出现错误:TypeError: unsupported operand type(s) for -: 'datetime.time' and datetime.time
    • 试试这个:from datetime import datetime, date datetime.combine(date.today(), current_time2) - datetime.combine(date.today(), current_time1)
    【解决方案4】:

    在 python 3.x 中使用time.perf_counter

    import time
    
    t1_start = time.perf_counter()
    
    do_something() # your code goes here
    
    t1_stop = time.perf_counter()
    print("Elapsed time:", t1_stop - t1_start) # print performance indicator
    

    【讨论】:

    • 虽然这可能“有效”测量时间增量,但它不提供时间跨度。
    猜你喜欢
    • 2010-09-13
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多