Python implements the method of calculating the number of days between two times

  • 2020-06-01 10:09:33
  • OfStack

This article illustrates an example of how the Python implementation calculates the number of days between two times. I will share it with you for your reference as follows:


#-*- encoding:UTF-8 -*-
from datetime import date
import time
nowtime = date.today()
def convertstringtodate(stringtime):
  " Converts the string type to date type "
  if stringtime[0:2] == "20":
    year=stringtime[0:4]
    month=stringtime[4:6]
    day=stringtime[6:8]
    begintime=date(int(year),int(month),int(day))
    return begintime
  else :
    year="20"+stringtime[0:2]
    month=stringtime[2:4]
    day=stringtime[4:6]
    begintime=date(int(year),int(month),int(day))
    return begintime
def comparetime(nowtime,stringtime):
  " Compare the two times , And returns the number of days between the two dates "
  if isinstance(nowtime,date):
    pass
  else:
    nowtime=convertstringtodate(nowtime)
  if isinstance(stringtime,date):
    pass
  else:
    stringtime=convertstringtodate(stringtime)
  result=nowtime-stringtime
  return result.days
"""
  if stringtime[0:2] == "20":
    year=stringtime[0:4]
    month=stringtime[4:6]
    day=stringtime[6:8]
    begintime=date(int(year),int(month),int(day))
    endtime=nowtime
    result=endtime-begintime
    return result.days
  else :
    year="20"+stringtime[0:2]
    month=stringtime[2:4]
    day=stringtime[4:6]
    begintime=date(int(year),int(month),int(day))
    endtime=nowtime
    result=endtime-begintime
    return result.days
"""
print isinstance("20141012",date)
print comparetime(nowtime,"140619")

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: