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:


#!/usr/bin/python
import time
import sys
def dateinput():
    date = raw_input('please input the first date: ')
    return date
def datetrans(tdate):
    spdate = tdate.replace("/","-")
    try:
        datesec = time.strptime(spdate,'%Y-%m-%d')
    except ValueError:
        print "%s is not a rightful date!!" % tdate
        sys.exit(1)
    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:
http://tools.ofstack.com/jisuanqi/date_jisuanqi

Online calendar:
http://tools.ofstack.com/bianmin/wannianli

Online lunar/solar calendar conversion tool:
http://tools.ofstack.com/bianmin/yinli2yangli

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: