0

I am trying to add date and time to the uploaded file.

If the filename is filename.xml then I would like to change the name to filename-<date>-<time>.xml

def handle_uploaded_file(self, f):
    name = "static/uploads/{0}".format(f.name)
    with open(name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

Any help is highly appreciated. Thanks in advance.

2
  • What kind of issues are you facing in the current approach ? Commented Sep 5, 2017 at 19:11
  • There are no issues currently. The file is uploading. How can I insert the date time with format(f.name) Commented Sep 5, 2017 at 19:14

3 Answers 3

2

You can use datetime module to get date and time separately.

Solution:

from datetime import datetime
def handle_uploaded_file(self, f):
    _datetime = datetime.now()
    datetime_str = _datetime.strftime("%Y-%m-%d-%H-%M-%S")
    # if there are more than one dots
    file_name_split = f.name.split('.')
    file_name_list = file_name_split[:-1]
    ext = file_name_split[-1]
    file_name_wo_ext = '.'.join(file_name_list)

    name = '/path/to/uploads/{0}-{1}.{2}'.format(file_name_wo_ext, datetime_str, ext)
    # rest of the code

Ref: datetime module in Python 3 docs

Follow this answer if you want to remove the microsecond component from time.

Sign up to request clarification or add additional context in comments.

10 Comments

Got this -- [Errno 22] Invalid argument: 'static/uploads/test.xml-2017-09-05-20:30:13.515619'
I am using Python 3.4
Are you on a Windows OS?
Yes I am on windows. Sorry I would have told this to you before.
colon (:) seem to be the issue in time. Let me update the answer.
|
0

You can use string concatenation with datetime module. Look below for the small snippet as an example.

import datetime
name = 'filename.xml'
name = name[:-4] + '_'+str(today.ctime()) + '_.xml'
print(name)

Comments

0
import datetime
date_time = datetime.datetime.now()
def handle_uploaded_file(self, f):
    name = "static/uploads/{0}".format(f.name)
    file_name,extension = name.split('.')
    modified_name = file_name+''+date_time
    name = modified_name+extension
    with open(name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

4 Comments

Getting an error date_time = datetime.now() AttributeError: 'module' object has no attribute 'now'
Made the correction, it should have been datetime.datetime.now()
Now getting - import datetime.datetime ImportError: No module named 'datetime.datetime'; 'datetime' is not a package
Made a slight correction, this code should work according to python 2.x but I'm not sure about 3.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.