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

时间:2017-10-12 09:20:32

标签: python python-3.x python-3.5 python-3.4 python-3.6

当我在下面运行我的查询时,它会创建一个名为“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)

提前谢谢!

3 个答案:

答案 0 :(得分:3)

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

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

使用datetime如下:

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)

答案 1 :(得分: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    

答案 2 :(得分:1)

将文件名变量设为file_name并使用datetime.now()

from datetime import datetime
file_name = 'mycsvfile' + str(datetime.now()) + '.csv'