Skip to content

Instantly share code, notes, and snippets.

@ifduyue
Created June 4, 2014 15:45
Show Gist options
  • Save ifduyue/f9eac401d1e42ce0a3b6 to your computer and use it in GitHub Desktop.
Save ifduyue/f9eac401d1e42ce0a3b6 to your computer and use it in GitHub Desktop.
#coding: utf8
import re
import time
import datetime
import dateutil.tz
# Remember offset is in seconds west of UTC, but the timezone is in
# minutes east of UTC.
def timestamp2rfc2822(timestamp, altzone=0):
offset = -altzone
hours, minutes = divmod(abs(offset), 3600)
sign = '+' if offset > 0 else '-'
zone = '%s%02d%02d' % (sign, hours, minutes // 60)
now = time.gmtime(timestamp+offset)
return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
now[2],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
now[0], now[3], now[4], now[5],
zone)
def timestamp2iso8601(timestamp, altzone=0):
offset = -altzone
hours, minutes = divmod(abs(offset), 3600)
sign = '+' if offset > 0 else '-'
zone = '%s%02d%02d' % (sign, hours, minutes // 60)
tz = dateutil.tz.tzoffset(zone, offset)
dt = datetime.datetime.utcfromtimestamp(timestamp)
dt = dt.replace(tzinfo=tz)
iso = dt.isoformat(' ')
# '2014-05-29 09:50:55+08:00' -> '2014-05-29 09:50:55 +08:00'
return iso[:-6] + ' ' + iso[-6:]
def timestamp2relative(timestamp, altzone=0):
dt = datetime.datetime.utcfromtimestamp(timestamp)
now = datetime.datetime.utcnow()
delta = now - dt
day = delta.days
second = delta.seconds
# Return quotient and remaining
qr = lambda a, b: (a / b, a % b)
year, day = qr(day, 365)
month, day = qr(day, 30)
hour, second = qr(second, 3600)
minute, second = qr(second, 60)
for period in ['year', 'month', 'day', 'hour', 'minute', 'second']:
n = eval(period)
if n > 0:
return ('%s %ss ago' if n > 1 else '%s %s ago') % (n, period)
return 'just now'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment