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
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.
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.
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.
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.
>>> 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
#!/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
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With