Python计算指定时间差的方法详解

Luna
Luna
发布时间:2026-10-13| 1人浏览过
原创

本文介绍如何在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

感谢阅读,希望本文能对大家有所帮助,欢迎继续支持本站!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。