Home > database >  How to set last modified time based on the request header 'Last-Modified' on Python
How to set last modified time based on the request header 'Last-Modified' on Python

Time:03-28

I want to get the last modified time from the url response header, and then write the response to a local file, and set the last modified time on that local file.

Here is the python code:

r = session.get(url)

url_time = r.headers['Last-Modified']

with open(file_name, 'wb') as f:
    f.write(r.content)
    
os.utime(file_name, (url_time, url_time))

Here is the error output:

TypeError: an integer is required (got type str)

How to convert the url_time to the specified "integer" for os.utime?

The code to print the url_time:

print("url_time: {}".format(url_time))

Here is the output of url_time:

url_time: Tue, 08 Feb 2022 14:32:27 GMT

CodePudding user response:

Here I use the datetime module to convert the string into a datetime object, then use that object to get the timestamp:

last_updated_pattern = "%a, %d %b %Y %H:%M:%S %Z"
timestamp = int(datetime.strptime(url_time, last_updated_pattern).timestamp())
os.utime(file_name, (timestamp, timestamp))

You can see the documentation for the format of the pattern for decoding time strings here. You may also want to review the documentation for the datetime object if it is not handling timezones or other properties of the time like you expect

  • Related