Python example of a method to calculate the number of days between two dates

  • 2020-06-01 10:21:14
  • OfStack

This example shows how Python calculates the number of days between two dates. I will share it with you for your reference as follows:

import time
import sys
def dateinput():
    date = raw_input('please input the first date: ')
    return date
def datetrans(tdate):
    spdate = tdate.replace("/","-")
        datesec = time.strptime(spdate,'%Y-%m-%d')
    except ValueError:
        print "%s is not a rightful date!!" % tdate
    return time.mktime(datesec)
def daysdiff(d1,d2):
    daysec = 24 * 60 * 60
    return int(( d1 - d2 )/daysec)
date1 = dateinput()
date2 = dateinput()
date1sec = datetrans(date1)
date2sec = datetrans(date2)
print "The number of days between two dates is: ",daysdiff(date1sec,date2sec)

PS: here are some other online tools for calculating dates and days that you can use:

Online date/days calculator:

Online calendar:

Online lunar/solar calendar conversion tool:

More about Python related content interested readers to view this site project: "skills summary Python date and time", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for you to design Python program.

Related articles: