【问题标题】:How to create a filename with the current date and time in python when query is ran运行查询时如何在python中创建具有当前日期和时间的文件名
【发布时间】:2018-03-24 04:05:30
【问题描述】:

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

提前谢谢你!

【问题讨论】:

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


【解决方案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)

【讨论】:

  • 嗨 Dinesh,当我使用您的方法时,我收到以下错误 - 回溯(最近一次调用最后一次):文件“C:/Users/.PyCharmCE2017.2/config/scratches/test1.py ", line 28, in with open(csv_file, 'w') as f: # Just use 'w' mode in 3.x OSError: [Errno 22] Invalid argument: 'myfile_2017-10-12_10:31: 12.csv'
  • 谢谢你!这行得通,但我只是想知道是否有另一种方法来格式化文件名。例如,现在的格式是 - mycsvfile2017-10-12_10_35_13。有没有办法让 mycsvfile2017-10-12_10:35:13
  • @DineshPundkar:否决票是因为文件名无效且缺乏解释,但您已经修复了前者,因此删除了否决票。
  • @Rich - 在文件名中使用下划线比任何其他特殊字符更好,因为它被广泛接受
  • @Dniesh,感谢您再次帮助我!我很感激!你很快就会看到我的更多帖子哈哈!谢谢
【解决方案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    

【讨论】:

  • 我会把它放在我的代码中的什么地方?请给我看代码
  • 你把它放在你打开文件的地方
  • @Silencer 你应该在格式中添加 .csv 并向他展示一个示例。
  • 好的,我已经修改了。
【解决方案3】:

有一个文件名变量file_name 并使用datetime.now()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2014-03-16
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多