运行查询时如何在python中使用当前日期和时间创建文件名 [英] How to create a filename with the current date and time in python when query is ran

查看:74
本文介绍了运行查询时如何在python中使用当前日期和时间创建文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I run my query below, it creates a file called ‘mycsvfile’. However is there a way to add the current date and timestamp when the CSV file is created? For example if I run this query now the file should be named mycsvfile20171012 – 10:00:00 (something like that).

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

Could someone edit my code and show me how to do this please?

我的代码:

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)

先谢谢你!

推荐答案

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

It is better to use underscore in filename than any other special character since it widely accepted Therefore constructing file name as below :

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中使用当前日期和时间创建文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆