代码之家  ›  专栏  ›  技术社区  ›  nad

如何将elasticsearch日期字段转换为typestamp字段

  •  0
  • nad  · 技术社区  · 4 年前

    ElasticSearch日志将时间输出为 date Mar 3, 2021 @ 11:59:30.705

    如何使用python将其转换为时间戳?假设输出类似于 1614730500000

    我特别需要把它转换成毫秒。

    我使用了下面的代码

    import time
    import datetime
    s = 'Mar 3, 2021 @ 11:59:30.705'
    form = '%b %d, %Y @ %H:%M:%S.%fz'
    time.mktime(datetime.datetime.strptime(s, form).timetuple())
    

    但它显示出错误

    ValueError: time data 'Mar 3, 2021 @ 11:59:30.705' does not match format '%b %d, %Y @ %H:%M:%S.%fz'
    

    请建议。

    0 回复  |  直到 4 年前
        1
  •  0
  •   nad    4 年前

    下面的解决方案解决了这个问题

    from datetime import datetime
    
    epoch = datetime.utcfromtimestamp(0)
    s = 'Mar 3, 2021 @ 11:59:30.705'
    form = '%b %d, %Y @ %H:%M:%S.%f'
    
    def unix_time_millis(datetime):
        return (datetime - epoch).total_seconds() * 1000.0
    
    current_date = datetime.strptime(s, form)
    print (unix_time_millis(current_date))