python之date


# -*- coding: utf-8 -*- from datetime import * import time # 1. date常用的类方法和类属性 #date对象所能表示的最大日期: 9999-12-31 print 'date.max',date.max #date对象所能表示的最小日期: 0001-01-01 print 'date.min',date.min #返回一个表示当前本地日期的date对象: 2012-09-12 print 'date.today():', date.today() #将Gregorian日历时间转换为date对象(Gregorian Calendar :一种日历表示方法,类似于我国的农历,西方国家使用比较多): #1347442385.972转换为2012-09-12 print 'date.fromtimestamp():', date.fromtimestamp(time.time()) # 2. date提供的实例方法和属性 #获得年 月 日 now = date(2012,9,17) print 'now.year:',now.year print 'now.month:',now.month print 'now.day:',now.day #date.replace(year, month, day):生成一个新的日期对象 #用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变) tomorrow = now.replace(day = 18) nextmonth = now.replace(month = 10) nextyear = now.replace(year = 2013) print "tomorrow:",tomorrow," nextyear:",nextyear," nextmonth:",nextmonth # 返回日期对应的time.struct_time对象; # print: time.struct_time(tm_year=2012, tm_mon=9, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=261, tm_isdst=-1) print "date.timetuple(): ",now.timetuple() # 返回日期对应的Gregorian Calendar日期; #print: 734763 print "date.toordinal(): ",str(now.toordinal()) #返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推; #print:0 print "date.weekday(): ",now.weekday() #返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推; #print: 1 print 'date.isoweekday(): ',now.isoweekday() #返回格式如(year,month,day)的元组; #print: (2012, 38, 1) print 'date.isocalendar():',now.isocalendar() #返回格式如'YYYY-MM-DD’的字符串; #print: '2012-09-17' print 'date.isoformat():',now.isoformat() #date.strftime(fmt):自定义格式化字符串。在下面详细讲解。 #3. 日期操作 #当前日期为2012年9月12日 now = date.today() tomorrow = now.replace(day = 13) delta = tomorrow - now print "now: ",now,"tomorrow: ",tomorrow #计算出间隔时间 #print: timedelta: 1 day, 0:00:00 print "timedelta: ",delta #print: now + delta = tomorrow : 2012-09-13 print "now + delta = tomorrow :",now + delta #print: tomorrow > now : True print "tomorrow > now :",tomorrow > now #print: tomorrow < now : False print "tomorrow < now :",tomorrow < now
from datetime import date

date.today()

             datetime.date(2017, 9, 27)
data(2018,10,24)

    datetime.date(2018, 10, 24)
date.today().year

    2017

data.today().month

    9

date.today().day

    27

date.today().strftime('%Y-%m-%d')

     '2017-09-27' 

date.today().ctime()
    'Wed Sep 27 00:00:00 2017'
 date.today().weekday()
                  2
date.today().timetuple()
     time.struct_time(tm_year=2017, tm_mon=9, tm_mday=27, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=270, tm_isdst=-1)


date = date.today()

    datetime.date(2017, 9, 27)

date.replace(day=19)

    datetime.date(2017, 9, 19)

date.today().isoformat()
                   '2017-09-27'

strftime中的格式,除了%y-%m-%d %H:%M:%D外,还有:

    %a  星期几,如Tue,Sar,Wed

    %b  月份,如Apr,May.

    %j  儒历日

    %x  YY/MM/DD格式(等于说是写了%x就代表是写了%y/%m/%d,下同)

    %X  HH:MM:SS格式

    %c  yy/mm/dd HH:MM:SS

    %W  第几周

 

 

 

 


    

 

posted @ 2017-09-27 16:20  sjfgod  阅读(1586)  评论(0编辑  收藏  举报