Python - How to calculate the elapsed time since X date?
Asked Answered
N

2

7

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,

Navaho answered 21/11, 2011 at 23:45 Comment(0)
H
11

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 use total_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.

Hindmost answered 21/11, 2011 at 23:51 Comment(2)
FWIW, str() called on a datetime.timedelta object creates a string formatted like: '4 days, 23:58:57.256000' I don't think there's a way to change the formatting, but it saves you some work if it's an acceptable format.Eaglewood
Excellent answer, but please note the relevant method of the timedelta class is total_secondsCatenane
L
3

I'd convert the submitted date into a datetime, then use something like https://gist.github.com/207624 to convert the datetime to a humanized string.

Lisabethlisan answered 21/11, 2011 at 23:48 Comment(1)
Hi. You have a simple error on the 9th line of your code. It says: dt = otherdate - now but really should be the other way around. Maybe that was the reason for the downvoter to vote down.Maynord

© 2022 - 2024 — McMap. All rights reserved.