Skip to content

Instantly share code, notes, and snippets.

@lee51
Created January 30, 2018 20:01
Show Gist options
  • Save lee51/5e418a19185ce6ec28ef4ec0e20a831e to your computer and use it in GitHub Desktop.
Save lee51/5e418a19185ce6ec28ef4ec0e20a831e to your computer and use it in GitHub Desktop.
RFC 7231-compliant (HTTP-date) timestamp in Python
import time
from wsgiref.handlers import format_date_time
# now
print format_date_time(time.time())
# epoch seconds
print format_date_time(1514764800)
@tantale
Copy link

tantale commented Apr 26, 2021

If you have an UTC date time object, you can use:

import datetime
from wsgiref.handlers import format_date_time

d = datetime.datetime.utcnow()
print(format_date_time(d.timestamp()))
# -> Mon, 26 Apr 2021 05:02:58 GMT

Regards
– Laurent.

@cerfedino
Copy link

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

@Invincibear
Copy link

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