Python计算两个日期之间相差天数的实现方法
本文介绍在Python中计算两个日期之间相差天数的具体实现方法。通过datetime模块处理字符串与日期对象的转换,并演示如何比较两个时间点以获取天数差。文中附带了实用的在线日期计算工具链接,供开发者快速验证日期数据。
本文详细介绍在Python中计算两个日期之间相差天数的具体实现方案,供读者参考学习。
#-*- encoding:UTF-8 -*-
from datetime import date
import time
nowtime = date.today()
def convertstringtodate(stringtime):
"把字符串类型转换为date类型"
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):
"比较两个时间,并返回两个日期之间相差的天数"
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")
此外,推荐几款常用的日期与天数计算在线工具,方便日常使用:
在线日期/天数计算器: http://tools.jb51.net/jisuanqi/date_jisuanqi
在线万年历日历: http://tools.jb51.net/bianmin/wannianli
在线阴历/阳历转换工具: http://tools.jb51.net/bianmin/yinli2yangli
如需了解更多Python相关知识,建议查阅本站专题:《Python日期与时间操作技巧总结》、《Python URL操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。
希望上述内容能对您的Python编程实践提供有益帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









