python中timedelta方法怎么用
2017-11-15
#! /usr/bin/python# coding=utf-8from 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"前"
#!/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)
#使用replace()代替日期加减
from datetime import datetime
now1 = datetime.now()
now1 # datetime.datetime(2017, 2, 10, 22, 29, 48, 288500)
# 增加一天或减少一天
now2 = now1.replace(day=9)
now2 # datetime.datetime(2017, 2, 9, 22, 29, 48, 288500)
# timestrap() 函数是把日期转化为时间戳,时间戳就是秒数
time_span = now1.timestrap() - now2.timestrap()/(24*3600)
time_span # 1
- >>> dtdatetime.datetime(2014, 4, 18, 15, 37, 7, tzinfo=<UTC>)>>> localtime(dt)datetime.datetime(2014, 4, 18, 23, 37, 7, tzinfo=<LocalTimezone>)
- >>> import datetime>>> now = datetime.datetime.now()>>> now - dt
- Traceback (most recent call last): File "<console>", line 1, in <module>TypeError: can't subtract offset-naive and offset-aware datetimes
- >>> dt = dt.replace(tzinfo=None)>>> dtdatetime.datetime(2014, 4, 18, 15, 37, 7)>>> now - dtdatetime.timedelta(0, 34108, 443000)
- begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d") while begin_date <= end_date:
date_str = begin_date.strftime("%m-%d")
date_list.append(date_str)
begin_date += datetime.timedelta(days=1) print date_list - # 方法2(安装boto3 库 pip install boto3):
- from datetime import datetime
- from dateutil.rrule import rrule, DAILY
- a = datetime(2009, 5, 30)
- b = datetime(2009, 6, 9)
- for dt in rrule(DAILY, dtstart=a, until=b):
- print dt.strftime("%Y-%m-%d")
- # 在原来日期上增加一年
- from dateutil.relativedelta import relativedelta
- from django.utils import timezone
- t1 = timezone.now()
- neww_year = t1 + relativedelta(years=1)
实例2:
‘’‘当前的时间上加一天或一年减一天等操作’‘’
日期常用问题
1: Datetime中offset-naive与offset-aware时间的计算
在使用Django时,默认是开启对多时区的支持的,在获取时间的时候会是如下形式:
datetime.datetime(2014, 4, 18, 15, 37, 7, tzinfo=<UTC>)
我们可以利用django.utils.timezone中提供的localtime方法来将该时间转换为本地时间:
1234有时候,我们需要将该时间与当前时间做比较,例如计算差值,你可能会想到直接这么做:
123不过这是不对的,并告知如下错误:
123问题就出在利用datetime.datetime.now()得到的当前时间是offset-naive的,而另外一个却是offset-aware的,因此我们需要将这里的dt转成与now一样的形式,可以这么做:
12345备注:1:timezone 获取的日期增加和修改(比如加一天减一天)
from django.utiles import timezone
from datetime
t1 = timezone.now()
# torrow
t1+datetime.timedelta(days=1,hours=1)
2:python得到两个时间段的每一天的列表
date_list = []