2017-10-12 84 views
1

当我在下面运行我的查询时,它会创建一个名为'mycsvfile'的文件。但是,在创建CSV文件时,是否有添加当前日期和时间戳的方法?例如,如果我现在运行这个查询文件应该命名为mycsvfile20171012 - 10:00:00(类似的东西)。如何在运行查询时在python中创建一个带有当前日期和时间的文件名

有人可以编辑我的代码,并告诉我如何做到这一点吗?

我的代码:

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) 

预先感谢您!

+0

看看在['datetime'](https://docs.python.org/3/library/datetime.html# (datetime.now()'](https://docs.python.org/3/library/datetime.html#datetime.datetime.now)和['datetime.strftime() '](https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime)。 – mhawke

回答

1

这是更好,因为它的文件名使用下划线比任何其他特殊字符广泛接受 因此构建文件的名称如下:

csv_file = 'myfile_' + str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) + '.csv' 

使用日期时间如下:

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) 

from datetime import datetime 
import os 

file_path = <PASS YOUR FILE HERE> 

csv_file = 'myfile_' + str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) + '.csv' 

csv_file_full = os.path.join(file_path, os.sep, csv_file) 

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

with open(csv_file_full, '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) 
+0

嗨Dinesh,我得到了以下错误,当我使用你的方法 - 回溯(最近调用最后): 文件“C:/Users/.PyCharmCE2017.2/config/scratches/test1.py”,第28行,在 with open(csv_file,'w')as f:#在3.x中只使用'w'模式 OSError:[Errno 22]无效参数:'myfile_2017-10-12_10:31:12.csv' – Rich

+0

i没有downvote它, – Rich

+0

谢谢你dinesh!这工作,但我只是想知道是有另一种方式来格式化文件的名称。例如,现在格式是 - mycsvfile2017-10-12_10_35_13。有没有办法让mycsvfile2017-10-12_10:35:13 – Rich

2

是的,你可以这样做: 然而“:”是不是在文件名中支撑20171010-10.00.00

>>> import time 
>>> fname = lambda : "mycsvfile{}.csv".format(time.strftime("%Y%m%d-%H.%M.%S")) 
>>> 
>>> fname() 
'mycsvfile20171012-17.24.59.csv' 

>>> with open(fname()) as f: 
>>> pass  
+0

我会在哪里把这个放在我的代码中?请给我看的代码 – Rich

+0

你把它放在你打开文件的地方 –

+0

@Silencer你应该添加.csv格式并向他展示一个例子。 –

0

有文件名的变量,file_name和使用datetime.now()

from datetime import datetime 
file_name = 'mycsvfile' + str(datetime.now()) + '.csv' 
相关问题