Get timestamp of sent and received data using Python requests library

Viewed 1881

using requests library of Python, is there any possibility to get the exact timestamp of received and sent data, e.g. headers or payload data?

Example:

import requests

url     = 'http://mytest.url'
headers = {'User-Agent': 'My Agent'}
payload = 'Hello World'

response = requests.post(url, payload, headers)

print response

Output (Note that headers and payload data may have different timestamps of reception!):

2019/10/09 13:00.05.12345 >> POST http://mytest.url HTTP/1.1
2019/10/09 13:00.05.67890 >> User-Agent: My Agent
2019/10/09 13:00.06.12345 >> Hello World
2019/10/09 13:00.10.12345 << HTTP/1.1 200 OK
2019/10/09 13:00.11.12345 << Connection: Keep Alive
2019/10/09 13:00.12.12345 << Hello My Agent

Greets, Steve

1 Answers

There is in fact a response.elapsed property that indicates how long the request took.

The best I think you can go about getting both the submission datetime and completed datetime is:

from datetime import datetime
import requests

url     = 'http://mytest.url'
headers = {'User-Agent': 'My Agent'}
payload = 'Hello World'

now = datetime.now()
response = requests.post(url, payload, headers)

elapsed = now + response.elapsed
Related