Skip to content

Commit 4ee4e22

Browse files
committed
python-ecosys/requests: Add way to read date-format response headers.
This is intended to make it easy to read the Last-Modified header, but it would work just as well for any of the other date-formatted HTTP response headers.
1 parent fee0e19 commit 4ee4e22

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

python-ecosys/requests/requests/__init__.py

+23
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,29 @@ def json(self):
4242

4343
return ujson.loads(self.content)
4444

45+
def get_date(self, k):
46+
import email.utils
47+
as_str = self.headers.get(k)
48+
if not as_str:
49+
return None
50+
return email.utils.parsedate_to_datetime(as_str)
51+
52+
def get_date_as_int(self, k):
53+
import datetime
54+
dt = self.get_date(k)
55+
if dt is None:
56+
return None
57+
if dt.tzinfo is None:
58+
dt = dt.replace(tzinfo=datetime.timezone.utc)
59+
else:
60+
dt = dt.astimezone(datetime.timezone.utc)
61+
62+
# dt.timestamp() returns a value of type float, but the number
63+
# inside that float will always be an integer in this case,
64+
# because the formats supported by parsedate_to_datetime()
65+
# only have 1 second resolution.
66+
return int(dt.timestamp())
67+
4568

4669
def request(
4770
method,

0 commit comments

Comments
 (0)