您的位置:首页 > 编程语言 > Python开发

Python中时间的处理之——timedelta篇

2016-10-31 19:30 357 查看
#!/usr/bin/python
#coding=utf-8

fromdatetimeimportdatetime,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',"最大"),
]
fork,vinattrs:
"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

#增加一个月
fromcalendarimportmonthrange
now+timedelta(days=monthrange(start.year,start.month)[1])


实例1:
'''时间d距离now()的长度,比如:1分钟前,1小时前,1月前,1年前'''

Python代码


#-*-encoding=UTF-8-*-

importdatetime

deftimebefore(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比较

ifnotisinstance(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分钟

ifbefore<=60:

returnu'刚刚'

forseconds,unitinchunks:

count=before//seconds

ifcount!=0:

break

returnunicode(count)+unit+u"前"

实例2:

‘’‘当前的时间上加一天或一年减一天等操作’‘’

Python代码1


#!/usr/bin/envpython

#-*-coding:utf-8-*-

fromdatetimeimportdatetime,timedelta

now=datetime.now()

yestoday=now-timedelta(days=1)

tommorow=now+timedelta(days=1)

next_year=now+timedelta(days=365)

Python代码2


#使用replace()代替日期加减

fromdatetimeimportdatetime

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

日期常用问题

1: Datetime中offset-naive与offset-aware时间的计算

在使用Django时,默认是开启对多时区的支持的,在获取时间的时候会是如下形式:

datetime.datetime(2014,4,18,15,37,7,tzinfo=<UTC>)

我们可以利用django.utils.timezone中提供的localtime方法来将该时间转换为本地时间:

有时候,我们需要将该时间与当前时间做比较,例如计算差值,你可能会想到直接这么做:

不过这是不对的,并告知如下错误:

问题就出在利用datetime.datetime.now()得到的当前时间是offset-naive的,而另外一个却是offset-aware的,因此我们需要将这里的dt转成与now一样的形式,可以这么做:

备注:1:timezone获取的日期增加和修改(比如加一天减一天)

fromdjango.utilesimporttimezone

fromdatetime

t1=timezone.now()

#torrow

t1+datetime.timedelta(days=1,hours=1)

2:python得到两个时间段的每一天的列表

date_list=[]
begin_date=datetime.datetime.strptime(begin_date,"%Y-%m-%d")
end_date=datetime.datetime.strptime(end_date,"%Y-%m-%d")
whilebegin_date<=end_date:
date_str=begin_date.strftime("%m-%d")
date_list.append(date_str)
begin_date+=datetime.timedelta(days=1)
printdate_list

# 方法2(安装boto3库 pipinstallboto3):

fromdatetimeimportdatetime
fromdateutil.rruleimportrrule,DAILY

a=datetime(2009,5,30)
b=datetime(2009,6,9)

fordtinrrule(DAILY,dtstart=a,until=b):
printdt.strftime("%Y-%m-%d")

# 在原来日期上增加一年


fromdateutil.relativedeltaimportrelativedelta
fromdjango.utilsimporttimezone
t1=timezone.now()
neww_year=t1+relativedelta(years=1)




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: