- 1 millisecond(毫秒) 转换成 1000 microseconds(微秒)
- 1 minute 转换成 60 seconds
- 1 hour 转换成 3600 seconds
- 1 week转换成 7 days
- 0 <= microseconds < 1000000
- 0 <= seconds < 3600*24 (the number of seconds in one day)
- -999999999 <= days <= 999999999
支持的操作有:
1 = t2 + t3 | 两个timedelta对象相加,同时满足 t1-t2 == t3 and t1-t3 == t2 为True |
t1 = t2 - t3 | 两个timedelta对象相减, 同时满足 t1 == t2 - t3 and t2 == t1 + t3 为True |
t1 = t2 * i or t1 = i * t2 | timedelta对象分别乘以i 同时满足 t1 // i == t2 为True, 且 i != 0 |
t1 = t2 // i | 向下取整,余数部分被丢弃 |
+t1 | 返回和t1相同值的timedelta对象 |
-t1 | 取反操作,等价于timedelta(-t1.days, -t1.seconds, -t1.microseconds)和 t1* -1 |
abs(t) | 绝对值,等价于: +t 当 t.days >= 0, -t 当 t.days < 0 |
str(t) | 返回字符串,格式为: [D day[s], ][H]H:MM:SS[.UUUUUU] |
repr(t) | 返回字符串,格式为: datetime.timedelta(D[, S[, U]]) |
- # -*- encoding=UTF-8 -*-
- import datetime
- def timebefore(d):
- chunks = (
- (60 * 60 * 24 * 365, u'年'),
- (60 * 60 * 24 * 30, u'月'),
- (60 * 60 * 24 * 7, u'周'),
- (60 * 60 * 24, u'天'),
- (60 * 60, u'小时'),
- (60, u'分钟'),
- )
- #如果不是datetime类型转换后与datetime比较
- if not isinstance(d, datetime.datetime):
- d = datetime.datetime(d.year,d.month,d.day)
- now = datetime.datetime.now()
- delta = now - d
- #忽略毫秒
- before = delta.days * 24 * 60 * 60 + delta.seconds #python2.7直接调用 delta.total_seconds()
- #刚刚过去的1分钟
- if before <= 60:
- return u'刚刚'
- for seconds,unit in chunks:
- count = before // seconds
- if count != 0:
- break
- return unicode(count)+unit+u"前"
实例2:
‘’‘当前的时间上加一天或一年减一天等操作’‘’
例子:
import time
import datetime
def datetime2timestamp(dt, convert_to_utc=False):
''' Converts a datetime object to UNIX timestamp in milliseconds. '''
if isinstance(dt, datetime.datetime):
if convert_to_utc: # 是否转化为UTC时间
dt = dt + datetime.timedelta(hours=-8) # 中国默认时区
timestamp = datetime.timedelta.total_seconds(dt - datetime.datetime(1970,1,1))
return long(timestamp)
return dt
def timestamp2datetime(timestamp, convert_to_local=False):
''' Converts UNIX timestamp to a datetime object. '''
if isinstance(timestamp, (int, long, float)):
dt = datetime.datetime.utcfromtimestamp(timestamp)
if convert_to_local: # 是否转化为本地时间
dt = dt + datetime.timedelta(hours=8) # 中国默认时区
return dt
return timestamp
def timestamp_utc_now():
return datetime2timestamp(datetime.datetime.utcnow())
print datetime.datetime.utcnow()
print timestamp_utc_now()