Python 的 timedelta:我不能直接获取我想要的整个差值的时间单位吗?

发布于 2024-07-13 09:59:26 字数 256 浏览 6 评论 0原文

自从在我的网站上发表帖子以来,我试图获得一些巧妙的日期(“自那以后的秒数、自那以后的几小时、自那以后的几周等......”)并且我正在使用存储在 utcnow 和 utc 日期之间的 datetime.timedelta 差异帖子的数据库。

看起来,根据文档,我必须使用天属性和秒属性来获取我想要的精美日期字符串。

我不能直接以我想要的任何时间单位来获取整个差异的值吗? 我错过了什么吗?

如果我能在几秒钟内得到全部差异,那就完美了。

I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.

Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want.

Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something?

It would be perfect if I could just get the entire difference in seconds.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浮世清欢 2024-07-20 09:59:26

看来Python 2.7引入了一个 total_seconds() 方法,我相信这就是您正在寻找的!

It seems that Python 2.7 has introduced a total_seconds() method, which is what you were looking for, I believe!

奢欲 2024-07-20 09:59:26

您可以计算出以秒为单位的差异。

total_seconds = delta.days * 86400 + delta.seconds

不,你并没有“错过什么”。 它不提供以秒为单位的增量。

You can compute the difference in seconds.

total_seconds = delta.days * 86400 + delta.seconds

No, you're no "missing something". It doesn't provide deltas in seconds.

∞觅青森が 2024-07-20 09:59:26

如果我能在几秒钟内得到整个差异,那就完美了。

那么“time”模块提供的 plain-old-unix-timestamp 可能更符合您的口味。

我个人还没有被“日期时间”中的很多内容所说服。

It would be perfect if I could just get the entire difference in seconds.

Then plain-old-unix-timestamp as provided by the 'time' module may be more to your taste.

I personally have yet to be convinced by a lot of what's in 'datetime'.

梦里寻她 2024-07-20 09:59:26

就像 bobince 所说,您可以使用时间戳,如下所示:

# assuming ts1 and ts2 are the two datetime objects
from time import mktime
mktime(ts1.timetuple()) - mktime(ts2.timetuple())

虽然我认为这比仅从 timedelta 对象计算秒更丑陋......

Like bobince said, you could use timestamps, like this:

# assuming ts1 and ts2 are the two datetime objects
from time import mktime
mktime(ts1.timetuple()) - mktime(ts2.timetuple())

Although I would think this is even uglier than just calculating the seconds from the timedelta object...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文