解决python 两个时间戳相减出现结果错误的问题
作者:gejiaming 时间:2023-01-18 17:41:44
如下所示:
两个时间相差一整天,结果却是相差时间为零 !!!!
这里是使用错误, .seconds只会计算 小时分钟秒 部分之间的差值
在这里使用total_seconds() 才是计算两个时间戳之间的相差时间
补充:Python 时间字符串、时间戳之间的转换,时间的加减
1、字符串转时间戳
import time
str_time = "20200713203740"
time_temp = time.strptime(str_time, "%Y%m%d%H%M%S") # 字符串格式化成时间格式
time_stamp = time.mktime(time_temp) # 格式化后的时间转换成时间戳
print(time_temp)
print(time_stamp)
结果如下:
time.struct_time(tm_year=2020, tm_mon=7, tm_mday=13, tm_hour=20, tm_min=37, tm_sec=40, tm_wday=0, tm_yday=195, tm_isdst=-1) 1594643860.0
2、时间戳转时间字符串
from datetime import datetime
x = 1594643860
y_m_d = datetime.fromtimestamp(x).strftime('%Y%m%d')
h_s_m = datetime.fromtimestamp(x).strftime('%H:%S:%M')
print(y_m_d)
print(h_s_m)
20200713
20:40:37
3、时间加天数
import datetime
# 将时间字符串转换成格式化的时间格式
time = "20190617 00:00:00"
time = datetime.datetime.strptime(time, "%Y%m%d %H:%M:%S")
# 在原来的时间上加6天
time = time + datetime.timedelta(days=6)
print(time)
# 将格式化的时间格式,转换成时间字符串
timestr = datetime.datetime.strftime(time, "%Y%m%d %H:%M:%S")
print(timestr)
2019-06-23 00:00:00
20190623 00:00:00
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/gejiaming/article/details/101123245
标签:python,时间戳,相减
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于pycharm的beautifulsoup4库使用方法教程
2022-12-05 22:47:05
![](https://img.aspxhome.com/file/2023/6/70806_0s.png)
Python百度指数获取脚本下载并保存
2023-01-05 23:47:44
![](https://img.aspxhome.com/file/2023/8/67878_0s.webp)
pyx文件 生成pyd 文件用于 cython调用的实现
2022-09-17 13:54:32
python dataframe NaN处理方式
2022-12-01 18:49:33
仿dw8代码折叠功能的HTML编辑器
2008-04-29 21:19:00
关于python下cv.waitKey无响应的原因及解决方法
2022-03-04 14:51:21
MHTML在ie7/vista bug 解决方案
2010-02-01 12:42:00
mysql 5.7.14 安装配置方法图文教程
2024-01-12 14:01:18
![](https://img.aspxhome.com/file/2023/7/96497_0s.jpg)
手把手教你从PyCharm安装到激活(最新激活码),亲测有效可激活至2089年
2021-06-16 19:53:55
![](https://img.aspxhome.com/file/2023/5/107575_0s.png)
python-pymysql如何实现更新mysql表中任意字段数据
2024-01-19 17:35:01
![](https://img.aspxhome.com/file/2023/4/78654_0s.png)
如何计算多个订单的核销金额
2024-01-26 17:56:31
![](https://img.aspxhome.com/file/2023/0/104140_0s.png)
Git原理和常用操作
2023-02-01 23:55:55
![](https://img.aspxhome.com/file/2023/7/123737_0s.png)
JS调用打印方法设置页眉页脚的实例
2024-04-22 12:45:58
MySQL对JSON类型字段数据进行提取和查询的实现
2024-01-23 02:48:54
![](https://img.aspxhome.com/file/2023/6/128016_0s.jpg)
pyqt5 实现 下拉菜单 + 打开文件的示例代码
2023-12-17 09:20:28
手写Vue源码之数据劫持示例详解
2023-07-02 17:01:28
python数据处理之如何修改索引和行列
2023-11-04 13:57:27
![](https://img.aspxhome.com/file/2023/7/64647_0s.png)
一个向上滚动代码
2010-02-10 12:29:00
![](https://img.aspxhome.com/file/UploadPic/20102/10/2010210123159245s.gif)
python实现将html表格转换成CSV文件的方法
2023-08-25 00:48:41
一篇文章带你搞懂Go语言标准库Time
2024-05-09 09:54:35