如何在Python中找到两个日期时间对象之间的时间差?
如何判断两个 datetime
对象之间的时间差(以分钟为单位)?
How do I tell the time difference in minutes between two datetime
objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(21)
我用这样的东西:
I use somethign like this :
这将给出以秒为单位的差异(然后除以 60 即可得到分钟):
输出:
在我看来,这是最简单的方法,您无需担心精度或溢出。
例如,使用
elapsedTime.seconds
会丢失很多精度(它返回一个整数)。此外,正如 这个答案 所指出的,elapsedTime.microseconds
的上限为 10^6。例如,对于 10 秒的sleep()
,elapsedTime.microseconds
给出8325
(这是错误的 ,应约为10,000,000
)。This will give the difference in seconds (then just divide by 60 to get minutes):
outputs:
This is the simplest way in my opinion, and you don't need to worry about precision or overflow.
For instance, using
elapsedTime.seconds
you lose a lot of precision (it returns an integer). Also,elapsedTime.microseconds
is capped at 10^6, as this answer pointed out. So, for example, for a 10 secondsleep()
,elapsedTime.microseconds
gives8325
(which is wrong, should be around10,000,000
).这是为了找出当前时间和上午 9.30 之间的差异
this is to find the difference between current time and 9.30 am
基于@Attaque伟大的答案,我提出了一个更短的简化版本的日期时间差计算器:
我已经更改它以避免声明重复函数,删除了漂亮的打印默认间隔,并添加了对毫秒、周和 ISO 月的支持(请记住,月份只是近似值,基于每个月等于
365/12
的假设)。其产生:
Based on @Attaque great answer, I propose a shorter simplified version of the datetime difference calculator:
I've changed it to avoid declaring repetetive functions, removed the pretty print default interval and added support for milliseconds, weeks and ISO months (bare in mind months are just approximate, based on assumption that each month is equal to
365/12
).Which produces:
这是我使用 mktime 的方法。
This is my approach using mktime.
以其他方式获取日期之间的差异;
所以得到最小的输出。
谢谢
In Other ways to get difference between date;
So get output in Min.
Thanks
我利用时间差进行持续集成测试来检查和改进我的功能。如果有人需要的话,这是简单的代码
使用:
并且我在日志输出中有类似的内容
I have used time differences for continuous integration tests to check and improve my functions. Here is simple code if somebody need it
Using:
and i have something like that in log output
您可能会发现这个快速片段在不太长的时间间隔内很有用:
在 Python v.3.8.6 上测试
You may find this fast snippet useful in not so much long time intervals:
tested on Python v.3.8.6
这是一个易于概括或转化为函数的答案,并且合理紧凑且易于遵循。
它以
Duration=270 天、10 小时、32 分钟和 42.13 秒的形式给出答案
Here is an answer that is easy to generalise or turn into a function and which is reasonable compact and easy to follow.
It gives an answer in the form
Duration=270 days, 10 hrs, 32 mins and 42.13 secs
开始时间 -->日期时间对象的开始时间
结束时间--> datetime 对象的结束时间
我们不能直接减去 datetime.time 对象
因此我们需要添加一个随机日期(我们使用组合)
或者您可以使用“今天”而不是 (1,1,1)
希望这会有所帮助
start_time --> start time for datetime object
end_time--> end time for datetime object
we cannot directly subtract the datetime.time objects
hence we need to add a random date to it (we use combine)
or you can use the "today" instead of (1,1,1)
hope this helps
这可能会帮助某人,用这种方法计算天数来查找是否过期。还有
dt.seconds
和dt.microseconds
也可用This might help someone, find is expired or not with this method its calculating with days. There are
dt.seconds
anddt.microseconds
also available从第一次中减去后来的时间
difference = later_time - first_time
创建一个仅保存差异的日期时间对象。在上面的示例中,它是 0 分 8 秒 562000 微秒。
Subtracting the later time from the first time
difference = later_time - first_time
creates a datetime object that only holds the difference.In the example above it is 0 minutes, 8 seconds and 562000 microseconds.
使用日期时间示例
以年为单位的持续时间
以天为单位的持续时间
以小时为单位的持续时间
以分钟为单位的持续时间
以秒为单位的持续时间
[!] 请参阅本文底部有关使用以秒为单位的持续时间的警告
以微秒为单位的持续时间
[!] 请参阅关于在本文底部使用以微秒为单位的持续时间的警告
两个日期之间的总持续时间
或简单地:
编辑 2019
的使用
由于这个答案已经受到关注,我将添加一个函数,这可能会简化某些警告:关于内置 .seconds 和 .microseconds 的警告
datetime.seconds
和datetime.microseconds
的上限分别为 [0,86400) 和 [0,10^6)。如果 timedelta 大于最大返回值,则应谨慎使用它们。
示例:
end
是start
之后 1h 和 200μs:end
是start
之后 1d 和 1h:Using datetime example
Duration in years
Duration in days
Duration in hours
Duration in minutes
Duration in seconds
[!] See warning about using duration in seconds in the bottom of this post
Duration in microseconds
[!] See warning about using duration in microseconds in the bottom of this post
Total duration between the two dates
or simply:
Edit 2019
Since this answer has gained traction, I'll add a function, which might simplify the usage for some
Warning: Caveat about built-in .seconds and .microseconds
datetime.seconds
anddatetime.microseconds
are capped to [0,86400) and [0,10^6) respectively.They should be used carefully if timedelta is bigger than the max returned value.
Examples:
end
is 1h and 200μs afterstart
:end
is 1d and 1h afterstart
:Python 2.7 中的新功能是
timedelta
实例方法.total_seconds()
。从 Python 文档来看,这相当于(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
。参考:http://docs.python.org/2/library/datetime.html# datetime.timedelta.total_seconds
New at Python 2.7 is the
timedelta
instance method.total_seconds()
. From the Python docs, this is equivalent to(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
.Reference: http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
只需将其中一个减去另一个即可。您将获得一个具有差异的
timedelta
对象。Just subtract one from the other. You get a
timedelta
object with the difference.如果
a
、b
是日期时间对象,那么要在 Python 3 中查找它们之间的时间差:在早期的 Python 版本上:
If
a
,b
是简单的日期时间对象,例如由datetime.now()
返回,那么如果对象表示具有不同 UTC 偏移量的本地时间(例如,在 DST 转换前后或过去),结果可能是错误的/未来的日期。更多详细信息:查找日期时间之间是否已过去 24 小时 - Python。要获得可靠的结果,请使用 UTC 时间或时区感知的日期时间对象。
If
a
,b
are datetime objects then to find the time difference between them in Python 3:On earlier Python versions:
If
a
,b
are naive datetime objects such as returned bydatetime.now()
then the result may be wrong if the objects represent local time with different UTC offsets e.g., around DST transitions or for past/future dates. More details: Find if 24 hrs have passed between datetimes - Python.To get reliable results, use UTC time or timezone-aware datetime objects.
使用divmod:
Use divmod:
要查找天数:timedelta 有一个“days”属性。你可以简单地查询一下。
To just find the number of days: timedelta has a 'days' attribute. You can simply query that.
这就是我获取两个 datetime.datetime 对象之间经过的小时数的方法:
This is how I get the number of hours that elapsed between two datetime.datetime objects:
只是认为提及有关时间增量的格式化可能会有用。 strptime() 根据格式解析表示时间的字符串。
这将输出:
0:05:00.518000
Just thought it might be useful to mention formatting as well in regards to timedelta. strptime() parses a string representing a time according to a format.
This will output:
0:05:00.518000
要获取
小时
、分钟
和秒
,您可以这样做To get the
hour
,minute
andsecond
, you can do this