Python How to calculate number of days between 2 dates?

14,890

Solution 1

Simpler implementation:

    import datetime

    d1 = datetime.datetime(2013,12,22)
    d2 = datetime.datetime(2014,2,15)
    (d2-d1).days

Solution 2

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) 
Share:
14,890

Related videos on Youtube

TheD0ubleT
Author by

TheD0ubleT

Hardcore gamer and casual programmer on python from time to time

Updated on September 16, 2022

Comments

  • TheD0ubleT
    TheD0ubleT over 1 year

    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
    TheD0ubleT almost 10 years
    instead of inputing dates directly can thay also be variables in the parentesis? and does it work with leap years?
  • yedpodtrzitko
    yedpodtrzitko almost 10 years
    yes, you can use variables there and yes, it works with a leap years