Python 随笔

1 时间戳转换成时间

import datetime

# 此处是以毫秒为单位的时间戳
timestamp = 1541550141417
# 转换成本地时间
array_date = datetime.datetime.fromtimestamp(timestamp)
# 转换成utc时间则使用
array_date = datetime.datetime.utcfromtimestamp(timeStamp)
# 
oTime = array_date.strftime("%Y-%m-%d %H:%M:%S")
print(oTime)

2 获取当前时间 

# 将现在的时间戳转换为想要的时间格式,time.tiem()获取的是以秒为单位但是后面有7位小数点。
rq = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.localtime(time.time()))
print(rq)
=>> 2018-11-07T17:47:04.000Z

print(time.time()) 
=>> 1541584024.2014368

3 字符串格式的字典转为字典

dict_str = "{"key1":'value_1', "key2":'value_2', "key3":'value_3'}"
new_dict = json.loads(dict_str)
print(new_dict["key1"])
=>> value_1
假如是数据库取出来的字符串字典,那存的时候前面的key一定要是双引号,否则取出来后转换不成功。

4 Python连接es之基础操作

from datetime import datetime
from elasticsearch import Elasticsearch
 
#创建索引调用create或index方法
es = Elasticsearch()
#已存在的不可重新创建
es.create(index="test-index2",doc_type="test-type",id=1,
          body={"any":"data","timesamp":datetime.now()})
     
es.create(index="test",doc_type="test-type",id=1,body={"any":"data","timesamp":datetime.now()})   

#删除索引
es.indices.delete(index="test-index2",ignore=[400,404])       
from elasticsearch import Elasticsearch 
# 连接es,并进行查询方法一
# 创建连接
es = Elasticsearch([{'host':'127.0.0.1','port':9200}])
index = "test"
query = {"aggs":{"all_times":{"terms":{"field":"@timestamp"}}}}
resp = es.search(index, body=query)
print(resp)
# 推荐这种
# 创建实例
es = Elasticsearch('es_ip', port=80, )

# index 为elasticsearch里面的index,是列表,后面可以接filter,query等,由于默认的只会打印10条出来,所以会在最后增加一个范围
sear = Search(using=es, index=["aa-*"],).filter('range', **{'@timestamp':{'from': int((time.time()-28800)*1000),'to':int(((time.time()-28799)*1000))}})[:500]


response = sear.execute()
 _source = response.to_dict()

# 关于里面的字段说明:hit:是从filter的结果都是在里面,total:总命中条数,
print("ShouTao匹配总数是", _source['hits']['total'])
# hits是一个列表需要遍历里面的内容。
for hit in _source["hits"]["hits"]:
    message = hit["_source"]
    #目标内容 
    print(message)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值