当我在下面运行我的查询时,它会创建一个名为'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)
预先感谢您!
看看在['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