$ python
Python
2.7
.
3
(default, Jan
2
2013
,
16
:
53
:
07
)
[GCC
4.7
.
2
] on linux2
Type
"help"
,
"copyright"
,
"credits"
or
"license"
for
more information.
>>>
import
datetime
>>> dtstr
=
'2014-02-14 21:32:12'
>>> datetime.datetime.strptime(dtstr,
"%Y-%m-%d %H:%M:%S"
).date()
datetime.date(
2014
,
2
,
14
)
>>>
''' 获取指定日期的上个月 日期字符串和日期格式 ''' 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)