我有两个unix日期的时间戳:
alvas@ubi:~$ date
Wed May 20 01:04:43 CEST 2015
如何计算时间戳对之间的时间差?
注意:我没有来自$date
的完整日期时间戳,但日志文件中只剩下hr:min:sec
中的时间。你知道吗
例如,timediff(start, end)
:
timediff('11:12:10', '19:58:50')
timediff('15:17:09', '03:11:10')
[输出]:
31600
42841
[输出2]:
8 hrs 46 mins 40 secs (31600 secs)
11 hrs 54 mins 1 secs (42841 secs)
如果end < start
,将其视为第二天。
我试过下面的脚本,但是有没有更简单的方法?你知道吗
def timediff(start, end):
start_hr, start_min, start_sec = map(float, start.split(':'))
end_hr, end_min, end_sec = map(float, end.split(':'))
if end_hr < start_hr:
end_hr = end_hr + 24
if end_min < start_min:
end_min = end_min + 60
end_hr -= 1
if end_sec < start_sec:
end_sec = end_sec + 60
end_min -= 1
num_hrs = end_hr - start_hr
num_mins = end_min - start_min
num_secs = end_sec - start_sec
total_seconds = 60*60*num_hrs + 60*num_mins+num_secs
total_time = " ".join([str(num_hrs), 'hrs', str(num_mins), 'mins', str(num_secs), 'secs'])
return total_seconds, total_time
print timediff('11:12:10', '19:58:50')
print timediff('15:17:09', '03:11:10')
[输出]:
(31600.0, '8.0 hrs 46.0 mins 40.0 secs')
(42841.0, '11.0 hrs 54.0 mins 1.0 secs')
当我尝试dateutil.parser.parse
时:
>>> from dateutil.parser import parse as dtparse
>>> dtparse('19:58:50') - dtparse('11:12:10')
datetime.timedelta(0, 31600)
>>> dtparse('03:11:10') - dtparse('15:17:09')
datetime.timedelta(-1, 42841)
你知道吗dateutil.parser文件(
pip install python-dateutil
)可以解析任何东西。。。以及它的时区意识在这里。。。这将工作,如果你不知道哪个时间戳是稍后。。。你知道吗
如果你想在顺序错误的情况下减去一天,试试这个
可能更容易使用datetime:
相关问题 更多 >
编程相关推荐