Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python human readable date difference

I have given date strings like these:

Mon Jun 28 10:51:07 2010
Fri Jun 18 10:18:43 2010
Wed Dec 15 09:18:43 2010

What is a handy python way to calculate the difference in days? Assuming the time zone is the same.

The strings were returned by linux commands.

Edit: Thank you, so many good answers

like image 676
user89021 Avatar asked Jun 28 '10 12:06

user89021


People also ask

How do I get the difference between dates in Python?

Using Python datetime module: In order to find the difference between two dates we simply input the two dates with date type and subtract them, which in turn provides us the number of days between the two dates.

Can you subtract dates in Python?

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.

How does Python calculate Timedelta?

To get a time difference in seconds, use the timedelta. total_seconds() methods. Multiply the total seconds by 1000 to get the time difference in milliseconds. Divide the seconds by 60 to get the difference in minutes.

Can Python read dates?

Thankfully, Python comes with the built-in module datetime for dealing with dates and times. As you probably guessed, it comes with various functions for manipulating dates and times. Using this module, we can easily parse any date-time string and convert it to a datetime object.


2 Answers

>>> import datetime
>>> a = datetime.datetime.strptime("Mon Jun 28 10:51:07 2010", "%a %b %d %H:%M:%S %Y")
>>> b = datetime.datetime.strptime("Fri Jun 18 10:18:43 2010", "%a %b %d %H:%M:%S %Y")
>>> c = a-b
>>> c.days
10
like image 113
Tim Pietzcker Avatar answered Nov 09 '22 10:11

Tim Pietzcker


#!/usr/bin/env python

import datetime

def hrdd(d1, d2):
    """
    Human-readable date difference.
    """
    _d1 = datetime.datetime.strptime(d1, "%a %b %d %H:%M:%S %Y")
    _d2 = datetime.datetime.strptime(d2, "%a %b %d %H:%M:%S %Y")
    diff = _d2 - _d1
    return diff.days # <-- alternatively: diff.seconds 

if __name__ == '__main__':
    d1 = "Mon Jun 28 10:51:07 2010"
    d2 = "Fri Jun 18 10:18:43 2010"
    d3 = "Wed Dec 15 09:18:43 2010"

    print hrdd(d1, d2)
    # ==> -11
    print hrdd(d2, d1)
    # ==> 10
    print hrdd(d1, d3)
    # ==> 169
    # ...
like image 26
miku Avatar answered Nov 09 '22 08:11

miku