Python - 如何计算自X日期以来经过的时间?
我有一个包含文章的数据库表,每一篇文章都有提交日期。我需要计算自文章在数据库中发布以来的天数和小时数,例如:
This article has been published 4 hours ago.
This article has been published 3 days and 4 hours ago.
已经有一些代码可以重复使用来执行此操作?我在谷歌上搜索过,但也许我没有使用正确的词。
有什么线索可以帮助我吗?
此致,
I have a database table with articles and each one of this articles have a submitted date. I need to calculate the days and hours since the article have been published in the database, like:
This article has been published 4 hours ago.
This article has been published 3 days and 4 hours ago.
There are already some code that I can reuse to do this? I've searched on google, but maybe I'm not using the correct words.
Any clue that could help me?
Best Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看
datetime
包,它拥有您想要的一切需要。当您从一个日期时间减去另一个日期时间时,您会得到一个
timedelta
对象。您可以使用total_seconds() 获取以秒为单位的持续时间,并使用除法将其转换为小时和天。那么你唯一的工作就是将其格式化为可读的字符串。Have a look at the
datetime
package, it has everything you need.when you subtract one datetime from another, you get a
timedelta
object. You can usetotal_seconds()
to get the duration in seconds and use division to convert it to hours and days. Then your only job then is to format it into a readable string.我会将提交的日期转换为
datetime
,然后使用类似 https:// gist.github.com/207624 将日期时间
转换为人性化字符串。I'd convert the submitted date into a
datetime
, then use something like https://gist.github.com/207624 to convert thedatetime
to a humanized string.