Last active
August 29, 2015 14:00
-
-
Save cansadadeserfeliz/11183145 to your computer and use it in GitHub Desktop.
Python: Get number of days passed between two datetime objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import calendar | |
def get_days_passed(before, after): | |
d1 = before.date() | |
d2 = after.date() | |
return abs(d1 - d2).days | |
d1 = datetime.datetime(2014, 05, 24, 17, 0, 0) | |
d2 = datetime.datetime(2014, 05, 24, 18, 5, 0) | |
print get_days_passed(d1, d2) # returns 0 | |
d1 = datetime.datetime(2014, 05, 24, 17, 0, 0) | |
d2 = datetime.datetime(2014, 05, 25, 5, 5, 0) | |
print get_days_passed(d1, d2) # returns 1 | |
d1 = datetime.datetime(2014, 05, 30, 17, 0, 0) | |
d2 = datetime.datetime(2014, 06, 1, 5, 5, 0) | |
print get_days_passed(d1, d2) # returns 2 |
@DavidToca gracias!
@oscar_lopez encontró una solución muy elegante: http://repl.it/Rgv/11
def get_days_passed_v2(before, after):
d1 = before.date()
d2 = after.date()
return (d1 - d2 if d1 > d2 else d2 - d1).days
la versión la más reciente de @oscar_lopez:
def get_days_passed_v2(before, after):
d1 = before.date()
d2 = after.date()
return abs(d1 - d2).days
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
import datetime
d1 = datetime.datetime(2014, 05, 24, 17, 0, 0)
d2 = datetime.datetime(2014, 05, 24, 18, 5, 0)
print (d2-d1).days # returns 1
d1 = datetime.datetime(2014, 05, 24, 17, 0, 0)
d2 = datetime.datetime(2014, 05, 25, 5, 5, 0)
print (d2-d1).days # returns 1
d1 = datetime.datetime(2014, 05, 30, 17, 0, 0)
d2 = datetime.datetime(2014, 06, 1, 5, 5, 0)
print (d2-d1).days # returns 2