# 获取日期: import datetime #调用事件模块 today =datetime.date.today() #获取今天日期 deltadays =datetime.timedelta(days=1) #确定日期差额,如前天 days=2 yesterday =today -deltadays # 获取差额日期,昨天 tomorrow =today +dletadays # 获取差额日期,明天 # 日期格式化输出 ISOFORMAT=’%Y%m%d’ #设置输出格式 print today.strftime(ISOFORMAT) dt = datetime.now() print '(%Y-%m-%d %H:%M:%S %f): ', dt.strftime('%Y-%m-%d %H:%M:%S %f') print '(%Y-%m-%d %H:%M:%S %p): ', dt.strftime('%y-%m-%d %I:%M:%S %p') print '%%a: %s ' % dt.strftime('%a') print '%%A: %s ' % dt.strftime('%A') print '%%b: %s ' % dt.strftime('%b') print '%%B: %s ' % dt.strftime('%B') print '日期时间%%c: %s ' % dt.strftime('%c') print '日期%%x:%s ' % dt.strftime('%x') print '时间%%X:%s ' % dt.strftime('%X') print '今天是这周的第%s天 ' % dt.strftime('%w') print '今天是今年的第%s天 ' % dt.strftime('%j') print '今周是今年的第%s周 ' % dt.strftime('%U') # # ---- 结果 ---- # (%Y-%m-%d %H:%M:%S %f): 2010-04-07 10:52:18 937000 # (%Y-%m-%d %H:%M:%S %p): 10-04-07 10:52:18 AM # %a: Wed # %A: Wednesday # %b: Apr # %B: April # 日期时间%c: 04/07/10 10:52:18 # 日期%x:04/07/10 # 时间%X:10:52:18 # 今天是这周的第3天 # 今天是今年的第097天 # 今周是今年的第14周 获取前一天,后一天的日期 datetime.date(2015,01,04)+datetime.timedelta(days=+1) datetime.date(2015,01,04)+datetime.timedelta(days=-1) #获取时间: import time #当前时间 time.strftime(“%Y-%m-%d %H:%M:%S”, time.localtime()) #获取上周日日期 isoformat = "%Y%m%d" lastsunday = datetime.date.today() - datetime.timedelta(days=datetime.date.today().isoweekday()) print lastsunday.strftime(isoformat) #获取上周日所有日期 def Getweek(): week = {} isoformat = "%Y%m%d" lastsunday = datetime.date.today() - datetime.timedelta(days=datetime.date.today().isoweekday()) sunday = int(lastsunday.strftime(isoformat)) week['Sun'] = sunday week['Sat'] = sunday - 1 week['Fri'] = sunday - 2 week['Thur'] = sunday - 3 week['Wed'] = sunday - 4 week['Tue'] = sunday - 5 week['Mon'] = sunday - 6 return week print Getweek() #当月第一天 import time,datetime d_today = datetime.datetime.today() d_first = datetime.datetime(d_today.year, d_today.month, 1) result = time.mktime(d_first.timetuple())