使用带有日期和时间的文件名失败 - Python pandas

Using file name with date and time fails - Python pandas

我一直在尝试在导出文件名时将时间戳添加到我的文件名中,字符串看起来不错,但是当我尝试将字符串包含在 to_csv 中时 Python 给出了一个错误。无法弄清楚为什么会这样。

file_name= 'TRANSACTIONS_' + str(datetime.now()) + '.csv'
Transaction.to_csv(file_name)

回溯

OSError                                   Traceback (most recent call last)
<ipython-input-95-9a18c677a3ab> in <module>
----> 1 Transaction.to_csv(file_name)

~\anaconda3\lib\site-packages\pandas\core\generic.py in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, date_format, doublequote, escapechar, decimal)
   3202             decimal=decimal,
   3203         )
-> 3204         formatter.save()
   3205 
   3206         if path_or_buf is None:

~\anaconda3\lib\site-packages\pandas\io\formats\csvs.py in save(self)
    186                 self.mode,
    187                 encoding=self.encoding,
--> 188                 compression=dict(self.compression_args, method=self.compression),
    189             )
    190             close = True

~\anaconda3\lib\site-packages\pandas\io\common.py in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text)
    426         if encoding:
    427             # Encoding
--> 428             f = open(path_or_buf, mode, encoding=encoding, newline="")
    429         elif is_text:
    430             # No explicit encoding

OSError: [Errno 22] Invalid argument: 'TRANSACTIONS_2020-11-10 12:34:53.622000.csv'

根据您的 OS,确保您创建的文件名仅包含允许的字符。例如。在 Windows 上,: 是不允许的,因此最好使用 strftime 指令,例如 %Y%m%d_%H%M%S:

file_name = f"TRANSACTIONS_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"

file_name
'TRANSACTIONS_20201110_082106.csv'