Python中时间的处理之——timedelta篇
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中时间的处理之——timedelta篇相关的知识,希望对你有一定的参考价值。
#! /usr/bin/python
# coding=utf-8
from datetime import datetime,timedelta
"""
timedelta代表两个datetime之间的时间差
"""
now = datetime.now()
past = past = datetime(2010,11,12,13,14,15,16)
timespan = now - past
#这会得到一个负数
past - now
attrs = [
("days","日"),( ‘seconds‘,"秒"),( ‘microseconds‘,"毫秒")
#(‘min‘,"最小"),( ‘max‘,"最大"),
]
for k,v in attrs:
"timespan.%s = %s #%s" % (k,getattr(timespan, k),v)
"""
总共相差的秒数
"""
timespan.total_seconds()
"""
实例化一个timespan
请注意它的参数顺序
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
"""
timespan = timedelta(days=1)
now - timespan #返回的是datetime型
now + timespan
timespan * 2 #还可以乘哦。代表二倍
timespan / 13
#增加一个月
from calendar import monthrange
now + timedelta(days=monthrange(start.year,start.month)[1])
实例1:
‘‘‘时间d距离now()的长度,比如:1分钟前,1小时前,1月前,1年前‘‘‘
- # -*- 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:
‘’‘当前的时间上加一天或一年减一天等操作’‘’
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- from datetime import datetime,timedelta
- now = datetime.now()
- yestoday = now - timedelta(days=1)
- tommorow = now + timedelta(days=1)
- next_year = now + timedelta(days = 365)
以上是关于Python中时间的处理之——timedelta篇的主要内容,如果未能解决你的问题,请参考以下文章