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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章