python 如何将字符串转化为datetime.date【获取指定日期的上月和两个日期之间相差的月数】
2016-03-31 17:23
881 查看
''' 获取指定日期的上个月 日期字符串和日期格式 ''' def getLastMonth(dtstr,dateformat): d=datetime.strptime(dtstr, dateformat).date() year = d.year month = d.month if month == 1 :#如果是本年1月的 month = 12 year -= 1 else :#如果是大于1月的 month -= 1 return (datetime(year,month,1)).strftime(dateformat) ''' 两个日期之间相差的月数 包括开始日期和结束日期的当天 日期字符串和日期格式 ''' def diffMonth(startDate,endDate,dateformat): start=datetime.strptime(startDate, dateformat).date() end=datetime.strptime(endDate, dateformat).date() startYear=start.year startMonth=start.month endYear=end.year endMonth=end.month #如果是同年 if startYear==endYear: diffmonths=endMonth-startMonth #如果是上年 elif endYear-startYear==1: diffmonths=12+endMonth-startMonth #如果是大于1年 elif endYear-startYear>1: years=endYear-startYear diffmonths=(years-1)*12+12+endMonth-startMonth #如果开始日期大约结束日期报错 elif endYear-startYear<0 or( endYear==startYear and endMonth-startMonth): print 'enddate must greater than startdate' return int(diffmonths+1)
相关文章推荐
- Python中使用中文导致的编码问题
- python字符串与数字的转化
- Python 学习-yield 用法和协程
- Python excel转xml
- leetcode-05- Longest Palindromic Substring-python
- Python 操作MySQL数据库
- Python 读取excel
- python安装Theano库
- Python:使用property装饰器将方法转为属性
- python笔记
- Python使用BeautifulSoup库解析HTML基本使用教程
- python urllib2使用心得
- python 打印颜色
- Python使用Mechanize模块编写爬虫的要点解析
- python webdriver 简单框架
- 深刻理解Python中的元类(metaclass)
- Python 中删除列表中所有的空元素
- 【Python】解决Django Admin管理界面样式表(CSS Style)丢失问题
- Python 安装Graphviz 画决策树
- leetcode04-Median of Two Sorted Arrays-python