os.rename a file to current date in python?
Question: I'm trying to create a zipped archive directory containing files. This will be
done daily so the name of the archive directory must include the date it was
created. I'm unable to rename the directory once it is created due to an
incorrect syntax. Below is the script I am using:

    
    
    import zipfile
    
    print('creating archive')
    zf = zipfile.ZipFile('archive.zip', mode='w')
    try:
        print('adding udp files')
        zf.write('test.udp')
    finally:
        print ('closing')
        zf.close()
    print('renaming archive...')
    import datetime
    dt = str(datetime.datetime.now())
    import os
    newname = 'file_'+dt+'.zip'
    os.rename('archive.zip', newname)
    print('renaming complete...')
    

Below is the error message I am receiving:

Traceback (most recent call last): File ".\archive.py", line 17, in
os.rename('archive.zip',newname) WindowsError: [Error 123] The filename,
directory name, or volume label syntax is incorrect

I'm using python 3.2. Please let me know if anything else is required.

Thanks, Paul


Answer: You are trying to rename your archive to something like

    
    
    file_2012-06-28 16:01:52.615855.zip
    

On Windows, `:` is not a valid character in a filename, so you need to choose
a different format, e.g. you could include the date only:

    
    
    >>> datetime.date.today().isoformat()
    '2012-06-28'
    

