Python 的 timedelta:我不能以任何时间单位获取我想要的整个差异的值吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/500168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:14:55  来源:igfitidea点击:

Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?

pythondatetimetimedelta

提问by Bjorn

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.

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

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.

看起来,根据文档,我必须使用 days 属性和 seconds 属性来获取我想要的花哨的日期字符串。

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.

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

回答by Ham

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

似乎Python 2.7引入了一个total_seconds()方法,这就是你要找的,我相信!

回答by S.Lott

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.

不,你没有“遗漏了什么”。它不会在几秒钟内提供增量。

回答by bobince

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.

然后,'time' 模块提供的纯旧 unix-timestamp 可能更符合您的口味。

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

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

回答by itsadok

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

就像 bobince 说的,你可以使用时间戳,像这样:

# 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 timedeltaobject...

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