I'm expanding a previous comment and a half answer to hopefully a usable answer.
This one produces to my knowledge a most correct and convenient cookie date format in a single fast function - accepted by any, even old and odd, browsers - accepts absolute & relative time:
import time
_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
_monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def cookie_date(epoch_seconds=None, future=0):
if not epoch_seconds:
epoch_seconds = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(epoch_seconds + future)
return "%s, %02d-%3s-%4d %02d:%02d:%02d GMT" % \
(_weekdayname[wd], day, _monthname[month], year, hh, mm, ss)
The function evolved from Cookie._getdate()
/ http.cookies._getdate()
, which produces spaces instead of the convenient -
's (ok according to RFC, but not recognized by all browser). This function allows only relative timing and is an undocumented function. However it can be used by the also undocumented feature, that you can give integer seconds (but not float!) for the expires field in SimpleCookie
morsels, which then are interpreted relative as seconds into the future / past:
cookie_morsel['expires'] = +3600 # 1h into future; 3600.0 doesn't work!
The frequently used time.strftime("%a, %d %b %Y %T GMT", t_expires)
is questionable, because it depends on locale settings (%a, %d) and an OS-specific undocumented format spec (%T not understood on Windows e.g.).