Created
January 30, 2018 20:01
-
-
Save lee51/5e418a19185ce6ec28ef4ec0e20a831e to your computer and use it in GitHub Desktop.
RFC 7231-compliant (HTTP-date) timestamp in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from wsgiref.handlers import format_date_time | |
# now | |
print format_date_time(time.time()) | |
# epoch seconds | |
print format_date_time(1514764800) |
This is how I did it:
from datetime import datetime
print(datetime.utcnow().strftime("%a, %d %b %G %T %Z"))
# -> Wed, 13 Apr 2022 10:12:21
Cheers
To convert a RFC 7231 string to datetime
, I used the following:
from datetime import datetime
datetime.strptime('Mon, 06 Feb 2023 07:03:53 GMT', '%a, %d %b %Y %H:%M:%S %Z')
which produced:
datetime.datetime(2023, 2, 6, 7, 3, 53)
You can do something like convert from RFC 7231 to ISO format:
datetime.strptime('Mon, 06 Feb 2023 07:03:53 GMT', '%a, %d %b %Y %H:%M:%S %Z').isoformat()
'2023-02-06T07:03:53'
You'll want to add a trailing 'Z' if the ISO timestamp is in UTC, something Python doesn't properly handle. Don't assume your timestamp is automatically UTC.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you have an UTC date time object, you can use:
Regards
– Laurent.