Python计算指定时间差的方法详解
本文介绍如何在Python中计算指定时间差,通过time模块实现获取过去或未来特定天、小时、分钟及秒数的时间。代码示例展示了UTC与本地时间的处理,以及三天前、两小时前等常见场景的用法,方便数据分析和日志处理时复用。
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
感谢阅读,希望本文能对大家有所帮助,欢迎继续支持本站!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













