Created
June 4, 2014 15:45
-
-
Save ifduyue/f9eac401d1e42ce0a3b6 to your computer and use it in GitHub Desktop.
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
#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