简体   繁体   English

Python - 如何计算自X日期以来经过的时间?

[英]Python - How to calculate the elapsed time since X date?

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, 最好的祝福,

Have a look at the datetime package , it has everything you need. 看看datetime ,它有你需要的一切。

when you subtract one datetime from another, you get a timedelta object. 当你从另一个中减去一个日期时间时,你得到一个timedelta对象。 You can use total_seconds() to get the duration in seconds and use division to convert it to hours and days. 您可以使用total_seconds()以秒为单位获取持续时间,并使用除法将其转换为小时和天。 Then your only job then is to format it into a readable string. 那么你唯一的工作就是将其格式化为可读的字符串。

我将提交的日期转换为datetime ,然后使用类似https://gist.github.com/207624的内容将datetime时间转换为人性化字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM