首页 > 代码库 > Python中时间的处理之——timedelta篇
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年前‘‘‘
Python代码
- # -*- 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:
‘’‘当前的时间上加一天或一年减一天等操作’‘’
Python代码
- #!/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篇
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。