如何在python中将从elasticsearch返回的64位时间戳转换为datetime?

2024-05-23 13:56:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的日期直方图查询返回如下结果:

"facets": {
  "hist": {
     "_type": "date_histogram",
     "entries": [
        {
           "time": 1385856000000,
           "count": 1884
        },
        {
           "time": 1385942400000,
           "count": 1902
        },

我怎么能得到2014年的时间值?在

以下是我目前所掌握的情况:

^{pr2}$

我回来了:

1601-01-02 14:37:23.520000
1601-01-02 14:37:32.160000
1601-01-02 14:37:40.800000
1601-01-02 14:37:49.440000
1601-01-02 14:37:58.080000
1601-01-02 14:38:06.720000
1601-01-02 14:38:15.360000

有什么想法吗?我刚从网上复制了getFiletime函数。我不认为这意味着我在做什么,但我知道这是在正确的轨道上。我尝试将“format”说明符放在我的弹性搜索查询中,但它不会像文档状态那样以字符串形式返回时间戳。任何帮助将不胜感激,并感谢您的阅读!在


Tags: 函数datetimetypecount时间情况直方图
3条回答

These aren't 64bit timestamps, just regular (unix epoch) ones with millisecond resolution:

 import datetime
 datetime.datetime.utcfromtimestamp(1385942400000 / 1000.).strftime('%Y-%m-%d')

gives 2013-12-02

(感谢@knutwalker上面的评论)

我也遇到了同样的挑战,我创造了这个方法来解决同样的问题。在

def to_es_date(d):
    s = d.strftime('%Y-%m-%dT%H:%M:%S.')
    s += '%03d' % int(round(d.microsecond / 1000.0))
    s += d.strftime('%z')
    return s

它接受带或不带时区的datetime,并返回一个ElasticSearch识别的字符串(当然是v1.1.1)。我不确定是否需要填充物,但它看起来很谨慎。在

^{pr2}$

一个简单的函数:

from datetime import datetime
import arrow

def timestamp(timestamp):
    date = datetime.fromtimestamp(timestamp /  1_000_000.0)
    return formattdatetime(date)

def formattdatetime(date):
    date = arrow.get(date, "YYYY-MM-DD")
    return arrow.get(date)

相关问题 更多 >