Python 的 timedelta:我不能直接获取我想要的整个差值的时间单位吗?
自从在我的网站上发表帖子以来,我试图获得一些巧妙的日期(“自那以后的秒数、自那以后的几小时、自那以后的几周等......”)并且我正在使用存储在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来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!
您可以计算出以秒为单位的差异。
不,你并没有“错过什么”。 它不提供以秒为单位的增量。
You can compute the difference in seconds.
No, you're no "missing something". It doesn't provide deltas in seconds.
那么“time”模块提供的 plain-old-unix-timestamp 可能更符合您的口味。
我个人还没有被“日期时间”中的很多内容所说服。
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'.
就像 bobince 所说,您可以使用时间戳,如下所示:
虽然我认为这比仅从
timedelta
对象计算秒更丑陋......Like bobince said, you could use timestamps, like this:
Although I would think this is even uglier than just calculating the seconds from the
timedelta
object...