2017-10-13 133 views
1

以下是我的代碼,它抓取數據並將數據轉換爲CSV文件(這是可行的)。我試圖只關注從午夜到下午4點(英國夏令時UTC/GMT +1小時)返回的數據,使用日期一些方法。如何在python中使用日期範圍來使用時間和日期來提取/查詢數據

有人可以告訴我這是怎麼做的,DTDT是日期。

如果我想達到的目標沒有意義,請告訴我,我會盡力解釋它。

我的代碼:

from elasticsearch import Elasticsearch 
import csv 

es = Elasticsearch(["9200"]) 

# Replace the following Query with your own Elastic Search Query 
res = es.search(index="search", body= 
       { 
        "_source": ["DTDT", "TRDT", "SPLE", "RPLE"], 
        "query": { 
         "bool": { 
          "should": [ 
           {"wildcard": {"CN": "TEST1"}} 

          ] 
         } 
        } 
}, size=10) 



header_names = { 'DTDT': 'DATE', 'TRDT': 'TIME', ...} 

with open('mycsvfile.csv', 'w') as f: # Just use 'w' mode in 3.x 
    header_present = False 
    for doc in res['hits']['hits']: 
     my_dict = doc['_source'] 
     if not header_present: 
      w = csv.DictWriter(f, my_dict.keys()) 
      w.writerow(header_names) # will write DATE, TIME, ... in correct place 
      header_present = True 


     w.writerow(my_dict) 

例如,我只想從午夜返回數據,直到下午2時(使用當前日期)。

+0

請問您能分享一行包含數據的csv文件嗎? –

+0

@ Dinesh,這些是CSV中的示例行。 13/10/2017 00:00 \t F#b422560 \t 2017年7月9日16時55 \t F#b422562 \t 2017年5月9日6點24 \t F#b422576 \t 2017年5月9日6點24 \t F#b422578 \t 25/08/2017 12時26 \t F#b422505 \t 13/10/2017 13時24分\t個B#r110576 \t 2017年8月9日二點53 \t B#r110585 \t 13/10/2017 14:00 \t B#r110594 \t 例如,文件時正在創建我想從午夜到下午6點的當前日期數據,因爲您可以看到有3行包含今天的數據,我只希望在文件 – Rich

+0

@Dinesh中顯示,想要進行聊天討論。當我粘貼行時,格式在評論框中出錯。不知道你是否可以正確看到它 – Rich

回答

0

在寫入csv文件之前,您可以檢查時間範圍,然後決定將它寫入文件。

添加以下功能來檢查時間範圍:

def time_in_range(start, end, x): 
    """Return true if x is in the range [start, end]""" 
    if start <= end: 
     return start <= x <= end 
    else: 
     return start <= x or x <= end 

它將如果給定的時間範圍內

然後在代碼中添加此。

import datetime 
#Range here(Midnight to 2 PM) 
start = datetime.time(0,0,0) 
end = datetime.time(14,0,0) 

with open('mycsvfile.csv', 'w') as f: # Just use 'w' mode in 3.x 
    header_present = False 
    for doc in res['hits']['hits']: 
     my_dict = doc['_source'] 
     if not header_present: 
      w = csv.DictWriter(f, my_dict.keys()) 
      w.writerow(header_names) # will write DATE, TIME, ... in correct place 
      header_present = True 

     #Get time 
     curr_time = my_dict['DTDT'] 
     #Conver it into datetime object 
     d_obj = datetime.datetime.strptime(curr_time, '%d/%m/%Y %H:%M') 
     #Check whether it is in range using above function 
     #If in range, then it will write to file 
     if time_in_range(start, end, d_obj.time()): 
      w.writerow(my_dict)