Reputation: 43
I need to use a Python program to download a file from an HTTP server while preserving the original timestamp of the file creation.
Accordingly, two questions:
Upvotes: 1
Views: 2229
Reputation: 2104
You could have a look at requests to download the file and get the modification date from the headers.
To set the dates you can use os.utime and email.utils.parsedate for parsing the date from the headers (see this answer by tzot).
Here is an example:
import datetime
import os
import time
import requests
import email.utils as eut
url = 'http://www.hamsterdance.org/hamsterdance/index-Dateien/hamster.gif'
r = requests.get(url)
f = open('output', 'wb')
f.write(r.content)
f.close()
last_modified = r.headers['last-modified']
modified = time.mktime(datetime.datetime(*eut.parsedate(last_modified)[:6]).timetuple())
now = time.mktime(datetime.datetime.today().timetuple())
os.utime('output', (now, modified))
Upvotes: 3