将弹性搜索时间戳属性转换为秒

x0v*_*x0v 1 python timestamp elasticsearch

我如何将此时间戳值转换为表示 python 中自纪元以来的秒数的整数

 2016-08-06T06:07:36.349Z
Run Code Online (Sandbox Code Playgroud)

这是我在弹性搜索查询中收到的时间戳值。

我尝试搜索,但时间戳格式与不同,对其他任何人都没有帮助

Sum*_*mar 5

您可以使用 python 内置的 datetime 包及其 strptime 方法将字符串转换为 datetime 对象。

from datetime import datetime
datetime.strptime("2016-08-06T06:07:36.349Z","%Y-%m-%dT%H:%M:%S.%fZ")
Run Code Online (Sandbox Code Playgroud)

之后你应该得到可以通过的纪元日期时间对象

epoch = datetime.utcfromtimestamp(0)
Run Code Online (Sandbox Code Playgroud)

你的最后几秒可以从这个方法中推导出来

def unix_time_millis(datetime):
    return (datetime - epoch).total_seconds() * 1000.0
Run Code Online (Sandbox Code Playgroud)

所以你的完整代码看起来像

from datetime import datetime

epoch = datetime.utcfromtimestamp(0)

def unix_time_millis(datetime):
    return (datetime - epoch).total_seconds() * 1000.0

current_date = datetime.strptime("2016-08-06T06:07:36.349Z","%Y-%m-%dT%H:%M:%S.%fZ")
print unix_time_millis(current_date)
Run Code Online (Sandbox Code Playgroud)

这个答案的灵感来自这个答案/sf/answers/777782421/