Search code examples
javapythonchronounit

Python compute timeframe length between two dates


I'm looking for the module ChronoUnit

java.time.temporal.ChronoUnit 

implementation in Python, found in Java 8.

The reason this modules is useful, is because it contains a procedure that computes the Days, Months, Years etc.. between to arbitrary dates.

PS: Implementing the date computation in python, can result in a lot of problems as there are a lot of corner cases that I simply have no time consider at the moment, so please be constructive while answering.

Edit: I think my question is not clear enough, but what I'm trying to accomplish is to be able to actually substract one date from another and as a result to get the months, days, years etc.. between the two.

As per juanpa.arrivillaga comment the arrow library provides a useful method that provides a near similar function, I think that I'll answer my own question now.


Solution

  • Thanks to @junpa.arrivillaga I figured out that the procedure might be easily implemented in python thanks to the arrow library.

    The api to be used it the following:

    arrow.Arrow.range('hour', start, end)
    

    The final method in Python would be:

    '''
        Computes day, month, year s 
        between two dates.
        frame - time frame 
        start - date start 
        end - date finish
        This method only works if the generated timeframe between to dates 
        is finite, as Arrow.range returns a generator!
    '''
    def count_frame_between_dates(frame, start, end):
        return len(list(arrow.Arrow.range(frame, start, end)))
    

    Edit: Arrow.range returns a generator, in theory you can't compute the length of a generator, but if you are sure the generator you're using is returning a finite set of elements then you can convert this generato into a list then use len() to compute it's length.

    Thanks to everyone.