python脚本中的时间delta参数

时间:2014-02-18 05:12:34

标签: datetime python-2.7

我是Python 2.7的新手。我有脚本输出一系列排序日期& timestamps和timedeltas(相对于上一个日期和时间戳):

2014-02-11 12:11:38.303000   0:00:00
2014-02-11 12:30:36.851000   0:18:58.548000
2014-02-11 13:58:33.776000   1:27:56.925000
2014-02-11 14:53:49.193000   0:55:15.417000
2014-02-12 09:32:40.186000   18:38:50.993000
2014-02-12 09:32:40.187000   0:00:00.001000
2014-02-12 09:37:50.535000   0:05:10.348000
2014-02-12 14:00:14.496000   4:22:23.961000
2014-02-13 08:51:52.554000   18:51:38.058000
2014-02-13 09:04:47.179000   0:12:54.625000
2014-02-13 09:05:26.359000   0:00:39.180000

我正在尝试合并并应用以下功能(使用下面的一些示例值):

time_parameter = 40000 #user-defined value in milliseconds (40000=40 seconds)
last_timestamp = 2014-02-13 09:04:47.179000
current_timestamp = 2014-02-13 09:05:26.359000
time_delta = 0:00:39.180000

if time_delta >= time_parameter:
    state = "expired"
else:
    state = "ongoing"

我的问题主要涉及如何编写这个时间参数,以便脚本理解它使用的是毫秒,我可以在if子句中使用这个值。我正在练习strftime的各种用途,但在找到解决方案时遇到了一些挫败感。希望找到一些答案或指导。

感谢

编辑笔记:

时间计算:

lastdtts = "default"
#...looping through timestamps with format: "14-02-11 08:35:41.526000"
    TimeStamp = line[0]      
    dtts = datetime.strptime(TimeStamp,"%y-%m-%d %H:%M:%S.%f")
    if lastdtts == "default":
        lastdtts = dtts
    tdelta=dtts-lastdtts
    lastdtts = dtts
    print "%s %s"%(dtts,tdelta) # 2014-02-13 09:05:26.359000   0:00:39.180000

1 个答案:

答案 0 :(得分:0)

如果time_delta的类型为timedelta,那么您可以将毫秒数转换为相同的类型:

limit_msec = 40000    # user-defined value in milliseconds
limit_timedelta = timedelta( milliseconds=limit_msec )

然后你可以测试它:

if time_delta >= limit_timedelta:
    state = "expired"