python获取指定时间差的时间实例详解

yipeiwu_com6年前Python基础

python获取指定时间差的时间实例详解

在分析数据的时间经常需要截取一定范围时间的数据,比如三天之内,两小时前等等时间要求的数据,因此将该部分经常需要用到的功能模块化,方便以后以后用到的时候复用。在此,也分享给大家。

import time 
import sys 
reload(sys) 
 
def get_day_of_day(UTC=False, days=0, hours=0, miutes=0, seconds=0): 
 ''''''' 
 if days>=0,date is larger than today 
 if days<0,date is less than today 
 date format = "YYYY-MM-DD" 
 ''' 
 now = time.time() 
 timeNew = now + days*24*60*60 + hours*60*60 + miutes*60 + seconds 
 if UTC : 
 timeNew = timeNew + time.timezone 
 t = time.localtime(timeNew) 
 return time.strftime('%Y-%m-%d %H:%M:%S', t) 
 
#使用UTC时间 两小时前 
t = get_day_of_day(True,0,-2) 
print t 
#当地时间 三天前 
t = get_day_of_day(False,-3) 
print t 
#当地时间 三天后 
t = get_day_of_day(False,3) 
print t

运行后所得结果:

2016-04-30 20:25:56 
2016-05-06 20:25:56

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Python2中文处理纪要的实现方法

python2不是以unicode作为基本代码字符类型,碰到乱码的几率是远远高于python3,但即便如此,相信很多人,也不想随意的迁移到python3,这里就总结几个我平常碰到的问题及...

基于python内置函数与匿名函数详解

基于python内置函数与匿名函数详解

内置函数 Built-in Functions abs() dict() help()...

flask中的wtforms使用方法

flask中的wtforms使用方法

一、简单介绍flask中的wtforms WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证。 安装: pip3 install wtforms...

windows 下python+numpy安装实用教程

如题,今天兜兜转转找了很多网站帖子,一个个环节击破,最后装好费了不少时间。 希望这个帖子能帮助有需要的人,教你一篇帖子搞定python+numpy,节约科研时间。 水平有限,难免存在不足...

Python查找函数f(x)=0根的解决方法

本文实例讲述了Python查找函数f(x)=0根的解决方法。分享给大家供大家参考。具体实现方法如下: ''' root = ridder(f,a,b,tol=1.0e-9). F...