比如从源头数据可以获得2个时间,其形式为
"2017-03-09 08:51:51 615"
"2017-03-09 08:52:21 601"
要计算前后者的时间差
自己百度搜索了很多相关内容,都无法解决这个问题,datetime不知道如何转换毫秒,timedelta无法转换年份
因为业务的精度要求,不能省略后面的毫秒,要计算两者的时间差。当然基本上都是同一天,但考虑到业务是24小时进行的,也不能忽略前面的日期,万一问题正好发生在0点前后呢
迷茫2017-04-18 10:36:51
datetime
可以转换毫秒的啊,精度都达到微秒了。或者说我没理解清楚问题?比如可以使用格式符%f
, as shown below:
>>> t1 = "2017-03-09 08:51:51 615"
>>> t2 = "2017-03-09 08:52:21 601"
>>> from datetime import datetime
>>> a = datetime.strptime(t1, "%Y-%m-%d %H:%M:%S %f")
>>> b = datetime.strptime(t2, "%Y-%m-%d %H:%M:%S %f")
>>> c = b - a
>>> c
datetime.timedelta(0, 29, 986000)
>>> c.microseconds
986000
Herec
the third one is microseconds.
巴扎黑2017-04-18 10:36:51
2017-03-09 08:51:51
Convert it to a timestamp and then connect the string to "615", which is a timestamp with millisecond precision. Can't the two timestamp values be calculated?
巴扎黑2017-04-18 10:36:51
The timestamp is in seconds, so multiplying by 1000 is milliseconds, and dividing microseconds by 1000 is also milliseconds
# coding: utf-8
from datetime import datetime
import time
format = '%Y-%m-%d %H:%M:%S %f'
a = datetime.strptime("2017-03-09 08:51:51 615", format)
b = datetime.strptime("2017-03-09 08:52:21 601", format)
t1 = time.mktime(a.timetuple()) * 1000 + a.microsecond / 1000
t2 = time.mktime(b.timetuple()) * 1000 + b.microsecond / 1000
print t2 - t1