Search code examples
pythonpandaswindowspython-datetime

Using file name with date and time fails - Python pandas


I've been trying to add the timestamp to my filename when I export it, the string seems fine but Python gives an error when I try to include the string in to_csv. Cant figure out why this is happening.

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

Traceback

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'

Solution

  • Depending on your OS, make sure the file name you create only contains allowed characters. E.g. on Windows, : is not allowed, so better use a strftime directive like for example %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'