gpt4 book ai didi

python - 运行查询时如何在 python 中创建具有当前日期和时间的文件名

转载 作者:太空宇宙 更新时间:2023-11-04 07:57:14 25 4
gpt4 key购买 nike

当我运行下面的查询时,它会创建一个名为“mycsvfile”的文件。但是,有没有办法在创建 CSV 文件时添加当前日期和时间戳?例如,如果我现在运行此查询,文件应命名为 mycsvfile20171012 – 10:00:00(类似名称)。

有人可以编辑我的代码并告诉我如何做吗?

我的代码:

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)

提前致谢!

最佳答案

最好在文件名中使用下划线而不是任何其他特殊字符,因为它被广泛接受因此构造文件名如下:

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)

关于python - 运行查询时如何在 python 中创建具有当前日期和时间的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46705867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com