如何在python中减去日期时间/时间戳 [英] How to subtract datetimes / timestamps in python
本文介绍了如何在python中减去日期时间/时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来应该很简单,但对于我的一生,我找不到答案。我从数据库中提取了两个日期时间/时间戳:
Seems like this should be so simple but for the life of me, I can't find the answer. I pull two datetimes/timestamps from the database:
2015-08-10 19:33:27.653
2015-08-10 19:31:28.209
如何从第二个减去第一个,最好是从结果中减去以毫秒为单位?是的,我也有日期,因为我也需要它在午夜左右工作。
How do I subtract the first from the second, preferably the result being in milliseconds? And yes, I have the date in there, too, because I need it to work at around midnight, as well.
推荐答案
将您的字符串解析为 datetime.datetime
对象并减去它们:
Parse your strings as datetime.datetime
objects and subtract them:
from datetime import datetime
d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")
print(d1 - d2)
给我:
0:01:59.444000
还要查看 timedelta
有关所有可能操作的文档。
Also check out timedelta
documentation for all possible operations.
这篇关于如何在python中减去日期时间/时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文