Python. Get file date and time (timestamp) from HTTP server

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:

  1. How to get file date from HTTP server using Python 3.7?
  2. How to set this date for the downloaded file?

Upvotes: 1

Views: 2229

Answers (1)

user7217806
user7217806

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

Related Questions