如何从时间字符串中减去 datenow?

How to subtract datenow from time string?

我有一个看起来很简单但我想不出来的问题。

我想实现以下目标: Time_as_string - time_now = 距离时间还剩分钟作为字符串。

我从网站上抓取时间作为字符串,例如:'15:30'

我想从中减去当前时间来显示多少分钟 一直保留到刮掉的时间字符串。

我尝试了很多方法,例如 strftime()、转换为 unix 时间戳、谷歌搜索解决方案等。 我可以通过 strftime() 从字符串中创建一个时间对象,但我不能从当前时间中减去它。

实现此目标的最佳方法是什么?

最简单的方法可能是将两个日期时间相减并使用 total_seconds():

>>> d1 = datetime.datetime(2000, 1, 1, 20, 00)
>>> d2 = datetime.datetime(2000, 1, 1, 16, 30)
>>> (d1 - d2).total_seconds()
12600.0

请注意,如果时间处于不同的时区,这将不起作用(我刚刚选择 2000 年 1 月 1 日作为日期时间)。否则,在相同的时区(或 UTC)中构造两个日期时间,减去它们并再次使用 total_seconds() 以获得以秒为单位的差异(剩余时间)。

from datetime import datetime

s = "15:30"
t1 = datetime.strptime(s,"%H:%M")

diff = t1 - datetime.strptime(datetime.now().strftime("%H:%M"),"%H:%M")

print(diff.total_seconds() / 60)
94.0

如果'15:30'属于今天:

#!/usr/bin/env python3
from datetime import datetime, timedelta

now = datetime.now()
then = datetime.combine(now, datetime.strptime('15:30', '%H:%M').time())
minutes = (then - now) // timedelta(minutes=1)

如果现在和那时之间有午夜,即如果 then 是明天;你可以考虑一个负差异(如果 then 相对于 now 似乎是过去的)是一个指标:

while then < now:
    then += timedelta(days=1)
minutes = (then - now) // timedelta(minutes=1)

在较旧的 Python 版本上,(then - now) // timedelta(minutes=1) 不起作用,您可以使用 (then - now).total_seconds() // 60 代替。

代码假定本地时区的 utc 偏移量相同 nowthen。参见 more details on how to find the difference in the presence of different utc offsets in this answer