Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 567
André Avatar asked Nov 21 '11 23:11

André


People also ask

How do I calculate the time difference between two dates in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.

How do you calculate end time and start time in Python?

hour = int(input("Starting time (hours): ")) mins = int(input("Starting time (minutes): ")) dura = int(input("Event duration (minutes): ")) print ("Event ending time: ",(hour + (mins + dura)//60)%24, ":", (mins + dura%60)%60, sep="")# Write your code here.

What is timespan in Python?

Timespans allow you to check if a timestamp falls within a specified list of boundaries. For example, you might want to program your phone system to only accept calls Mon-Fri from 9 a.m. to 5 p.m. except on holidays like Christmas. Timespans are specified in the form of times|daysofweek|days|months.


2 Answers

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.

like image 118
Mark Ransom Avatar answered Sep 23 '22 15:09

Mark Ransom


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.

like image 43
David Wolever Avatar answered Sep 19 '22 15:09

David Wolever