3

I'm having trouble doing this in a clean and simple way in python.
What I'd like to do is having a piece of code that calculates the number of days passed between 2 dates. For example today being the 22nd of december and i want to know how many days i have before the 15th of febuary. There are 55 days difference
(i took this example because it englobes 2 different years an multiple months)
What i made was very messy and dosen't work half the time so i'm kind of embarrassed to show it.
Any help is appreciated.
Thanks in advance

TheD0ubleT
  • 51
  • 1
  • 1
  • 11
  • Use the datetime module - see http://stackoverflow.com/questions/151199/how-do-i-calculate-number-of-days-betwen-two-dates-using-python – dannymilsom Jun 17 '14 at 16:11

2 Answers2

13

Simpler implementation:

    import datetime

    d1 = datetime.datetime(2013,12,22)
    d2 = datetime.datetime(2014,2,15)
    (d2-d1).days
gkusner
  • 1,244
  • 1
  • 11
  • 14
3

just create an instance of both the dates and substract them - you'll get timedelta object with a given info.

>>> from datetime import date
>>> by = date(2013, 12, 22)
>>> since = date(2014, 2, 15)
>>> res = since - by
>>> res.days
55

some examples with a variables

>>> variables_tuple = (2013, 12, 22)
>>> by = date(*variables_tuple)
>>> by.year
2013
>>> until_year = 2014
>>> until = date(until_year, 2, 15) 
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42