python利用datetime模块计算时间差
作者:lastme 时间:2021-10-07 01:02:04
今天写了点东西,要计算时间差,我记得去年写过,于是今天再次mark一下,以免自己忘记
In [27]: from datetime import datetime
In [28]: a=datetime.now()
In [29]: b=datetime.now()
In [32]: a
Out[32]: datetime.datetime(2015, 4, 7, 4, 30, 3, 628556)
In [33]: b
Out[33]: datetime.datetime(2015, 4, 7, 4, 34, 41, 907292)
In [34]: str(a) 字符串的转换,用户储存到文本或者数据库
Out[34]: '2015-04-07 04:30:03.628556'
In [35]:datetime.strptime(str(a),"%Y-%m-%d %H:%M:%S.%f")
Out[35]:datetime.datetime(2015, 4, 7, 4, 30, 3, 628556)
In [36]: (b-a)
Out[36]: datetime.timedelta(0, 278, 278736)
In [37]: (b-a).seconds 时间差的计算,单位为秒
Out[37]: 278
Q:如何方便的计算两个时间的差,如两个时间相差几天,几小时等
A:使用datetime模块可以很方便的解决这个问题,举例如下:
>>> import datetime
>>> d1 = datetime.datetime(2005, 2, 16)
>>> d2 = datetime.datetime(2004, 12, 31)
>>> (d1 - d2).days
47
上例演示了计算两个日期相差天数的计算。
import datetime
starttime = datetime.datetime.now()
#long running
endtime = datetime.datetime.now()
print (endtime - starttime).seconds
上例演示了计算运行时间的例子,以秒进行显示。
>>> d1 = datetime.datetime.now()
>>> d3 = d1 + datetime.timedelta(hours=10)
>>> d3.ctime()
上例演示了计算当前时间向后10小时的时间。
其本上常用的类有:datetime和timedelta两个。它们之间可以相互加减。每个类都有一些方法和属性可以查看具体的值,如datetime可以查看:天数(day),小时数(hour),星期几(weekday())等;timedelta可以查看:天数(days),秒数(seconds)等。
以上所述就是本文的全部内容了,希望大家能够喜欢。
标签:Python,datetime,时间差
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何Tkinter模块编写Python图形界面
2021-03-12 20:04:50
![](https://img.aspxhome.com/file/2023/3/97273_0s.jpg)
SQL语言基本语句介绍
2008-07-24 13:32:00
Python中异常捕获与处理的方法总结
2023-12-10 07:48:24
![](https://img.aspxhome.com/file/2023/8/95898_0s.png)
flask开启多线程的具体方法
2023-03-10 06:30:50
python 使用cycle构造无限循环迭代器
2022-08-19 13:09:10
![](https://img.aspxhome.com/file/2023/9/89359_0s.png)
php实现mysql备份恢复分卷处理的方法
2023-11-16 20:55:33
Python深度学习之Keras模型转换成ONNX模型流程详解
2023-01-02 00:32:44
解决nohup重定向python输出到文件不成功的问题
2024-01-01 08:24:03
如何用表单在线建立目录?
2010-06-16 09:49:00
python神经网络Pytorch中Tensorboard函数使用
2021-03-30 04:27:01
![](https://img.aspxhome.com/file/2023/3/78583_0s.png)
用python实现五子棋实例
2022-08-23 21:42:38
![](https://img.aspxhome.com/file/2023/8/65908_0s.jpg)
Python使用matplotlib实现在坐标系中画一个矩形的方法
2022-05-13 00:19:13
![](https://img.aspxhome.com/file/2023/7/97077_0s.jpg)
SQL Server Table中XML列的操作代码
2011-11-03 17:18:16
利用XMLHTTP无刷新自动实时更新数据
2008-02-19 18:29:00
标签明晰、有效
2010-01-18 12:22:00
pyqt5使用按钮进行界面的跳转方法
2022-10-25 16:42:24
使用Python的turtle模块画国旗
2021-10-22 12:31:10
![](https://img.aspxhome.com/file/2023/4/93724_0s.jpg)
Python利用flask sqlalchemy实现分页效果
2023-10-05 16:36:21
![](https://img.aspxhome.com/file/2023/5/86185_0s.jpg)
Django中提示消息messages的设置方式
2021-08-14 20:40:51
Sqlserver 2000/2005/2008 的收缩日志方法和清理日志方法
2012-07-21 14:55:18