• python:datetime类常用内容


    datetime类常用内容

    代码

    from datetime import datetime
    from datetime import date
    import time
    
    
    #datetime()和time()
    """
    datetime模块的常用类:
      date:日期,常用属性:year、month、day
      time:时间
      datetime:日期时间,常用属性:hour、minute、second、microsecond
      timedelta:时间间隔,两个时间点之间的长度
    datetime模块中的常量:
    MAXYEAR,datetime.MAXYEAR最大年份
    MINYEAR,datetime.MINYEAR最小年份
    """
    
    
    #(一)date类
    td = datetime.today()
    print ("Today is ",td)                  #获取当前日期、时间:2019-11-24 20:17:28.933784
    #获取当前年月日的方法一
    print ("Today's year is ",td.year)      #当前年:2019
    print ("Today's month is ",td.month)    #当前月:11
    print ("Today's day is ",td.day)        #当前日:24
    
    #获取当前年月日的方法二:.__getattribute__()方法
    print ("20191102's year is ",td.__getattribute__("year"))      #当前年:2019
    print ("20191102's month is ",td.__getattribute__("month"))    #当前月:11
    print ("20191102's day is ",td.__getattribute__("day"))        #当前日:24
    
    
    #.fromtimestamp()方法,通过给定的时间戳,返回对应的date对象
    print (datetime.fromtimestamp(time.time()))                    #2019-11-25 06:59:23.325629
    print (datetime.utcfromtimestamp(time.time()))                 #2019-11-24 22:59:23.325629 差8小时
    print (date.fromtimestamp(time.time()))                        #2019-11-25
    
    print (datetime.now())                                         #2019-11-25 06:59:23.325629
    print (datetime.now().date())                                  #2019-11-25
    print (datetime.now().time())                                  #06:59:23.325629
    print (datetime.utcnow())                                      #2019-11-24 22:59:23.325629 差8小时
    print (time.time())                                            #1574636363.3256292
    
    print (datetime.today())                                       #2019-11-25 07:03:10.692589
    print (datetime.today().date())                                #2019-11-25
    print (date.today())                                           #2019-11-25
    
    
    """用于日期比较大小的方法:
    方法名        方法说明            用法
    __eq__(…)    等于(x==y)        x.__eq__(y)
    __ge__(…)    大于等于(x>=y)    x.__ge__(y)
    __gt__(…)    大于(x>y)        x.__gt__(y)
    __le__(…)    小于等于(x<=y)    x.__le__(y)
    __lt__(…)    大于(x<y)        x.__lt__(y)
    __ne__(…)    不等于(x!=y)        x.__ne__(y)
    __sub__(…)     x - y            x.__sub__(y)
    __rsub__(…)     y - x            x.__rsub__(y)
    """
    
    a=date(2017,3,1)
    b=date(2017,3,15)
    
    print("a=b,a.__eq__(b)",a.__eq__(b))                            #
    print("a≥b,a.__ge__(b)",a.__ge__(b))                            #
    print("a>b,a.__gt__(b)",a.__gt__(b))                            #
    print("a≤b,a.__le__(b)",a.__le__(b))                            #
    print("a<b,a.__lt__(b)",a.__lt__(b))                            #
    print("a!=b,a.__ne__(b)",a.__ne__(b))                           #
    print("a-b,.__sub__(b)",a.__sub__(b))                           # -14 days, 0:00:00
    print("b-a,a.__rsub__(b)",a.__rsub__(b))                        # 14 days, 0:00:00
    print("a-b,.__sub__(b)",a.__sub__(b).days)                      # -14(获取相差的天数,使用.days)
    print("b-a,a.__rsub__(b)",a.__rsub__(b).days)                   # 14 (获取相差的天数,使用.days)
    
    """
    日期符合ISO标准,三个方法:
        1、isocalendar(...):返回包含三个值的元组,依次为:year年份,week number周数,weekday星期数(周一为1…周日为7):
        2、isoformat(...): 返回符合ISO 8601标准 (YYYY-MM-DD) 的日期字符串
        3、isoweekday(...): 返回符合ISO标准的指定日期所在的星期数(周一为1…周日为7)
    """
    print (a.isocalendar())                                             #(2017, 9, 3)
    print (a.isocalendar()[0])                                          #获取年
    print (a.isocalendar()[1])                                          #获取周数
    print (a.isocalendar()[2])                                          #获取星期
    
    print (a.isoformat())                                               #2017-03-01
    print (a.isoweekday())                                              #获取周数
    print (a.weekday())                                                 #获取星期,周一为0
    
    
    """
    格式化日期:date转为str,日期转为字符串显示
    __format__(...)方法以指定格式进行日期输出(与此方法等价的方法为strftime(...)),或者使用.__str__()方法
    """
    print (a.__str__())                                                          #2017-03-01
    print (a.__format__("%Y-%m-%d"))                                             #2017-03-01
    print (a.strftime("%Y-%m-%d"))                                               #2017-03-01
    
    print (a.__format__("%Y/%m/%d"))                                             #2017/03/01(大写的Y)
    print (a.strftime("%Y/%m/%d"))                                               #2017/03/01(大写的Y)
    
    print (a.__format__("%Y%m%d"))                                             #20170301(大写的Y)
    print (a.strftime("%Y%m%d"))                                               #20170301(大写的Y)
    
    print (a.__format__("%y/%m/%d"))                                             #17/03/01(小写的y)
    print (a.strftime("%y/%m/%d"))                                               #17/03/01(小写的y)
    
    print (a.__format__("%D"))                                                   #03/01/17
    print (a.strftime("%D"))                                                     #03/01/17
    
    
    
    
    #日期练习题;计算日期差,方法一:直接减
    sum = 0
    dates = ['2019-1-2','2019-1-27','2019-2-25','2019-3-25','2019-4-22','2019-5-20','2019-6-16','2019-7-19','2019-8-15','2019-9-10','2019-10-9','2019-10-31','2019-11-24']
    for i in range(len(dates)-1):
        dateq = datetime.strptime(dates[i],'%Y-%m-%d').date()      #字符串格式转为日期格式
        dateh = datetime.strptime(dates[i+1],'%Y-%m-%d').date()    #字符串格式转为日期格式
        print(dateq,dateh,end='')                                  #,end=''不换行,在行尾显示一个空格
        datec =dateh -dateq                                        #两个日期的差
        print ('相隔:',datec.days)
        sum += datec.days
    print ("总相隔:",sum,"次数:",len(dates)-1)
    print("平均总相隔:%.2f" %(sum/(len(dates)-1)))
    
    
    #日期练习题;计算日期差,方法二:使用__sub__()方法
    sum = 0
    dates = ['2019-1-2','2019-1-27','2019-2-25','2019-3-25','2019-4-22','2019-5-20','2019-6-16','2019-7-19','2019-8-15','2019-9-10','2019-10-9','2019-10-31','2019-11-24']
    for i in range(len(dates)-1):
        dateq = datetime.strptime(dates[i],'%Y-%m-%d').date()      #字符串格式转为日期格式
        dateh = datetime.strptime(dates[i+1],'%Y-%m-%d').date()    #字符串格式转为日期格式
        print(dateq,dateh,end='')                                  #,end=''不换行,在行尾显示一个空格
        datec =dateh.__sub__(dateq)                                #两个日期的差
        print ('相隔:',datec.days)
        sum += datec.days
    print ("总相隔:",sum,"次数:",len(dates)-1)
    print("平均总相隔:%.2f" %(sum/(len(dates)-1)))
    
    """
    #常见错误:
    
    问题:TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
    原内容:
        from datetime import date
        a = datetime.date(2017,3,1)
    原因:导入模块时,是从datetime模块中导入了date,所以在写date类时,直接写即可,不用再加datetime
    修改后内容:
        from datetime import date
        a = date(2017,3,1)
        或
        import datetime
        a = datetime.date(2017,3,1)
    """

     结果

    Today is  2019-11-25 07:22:49.569223
    Today's year is  2019
    Today's month is  11
    Today's day is  25
    20191102's year is  2019
    20191102's month is  11
    20191102's day is  25
    2019-11-25 07:22:49.569223
    2019-11-24 23:22:49.569223
    2019-11-25
    2019-11-25 07:22:49.569223
    2019-11-25
    07:22:49.569223
    2019-11-24 23:22:49.569223
    1574637769.5692234
    2019-11-25 07:22:49.569223
    2019-11-25
    2019-11-25
    a=b,a.__eq__(b) False
    a≥b,a.__ge__(b) False
    a>b,a.__gt__(b) False
    a≤b,a.__le__(b) True
    a<b,a.__lt__(b) True
    a!=b,a.__ne__(b) True
    a-b,.__sub__(b) -14 days, 0:00:00
    b-a,a.__rsub__(b) 14 days, 0:00:00
    a-b,.__sub__(b) -14
    b-a,a.__rsub__(b) 14
    (2017, 9, 3)
    2017
    9
    3
    2017-03-01
    3
    2
    2017-03-01
    2017-03-01
    2017-03-01
    2017/03/01
    2017/03/01
    20170301
    20170301
    17/03/01
    17/03/01
    03/01/17
    03/01/17
    2019-01-02 2019-01-27相隔: 25
    2019-01-27 2019-02-25相隔: 29
    2019-02-25 2019-03-25相隔: 28
    2019-03-25 2019-04-22相隔: 28
    2019-04-22 2019-05-20相隔: 28
    2019-05-20 2019-06-16相隔: 27
    2019-06-16 2019-07-19相隔: 33
    2019-07-19 2019-08-15相隔: 27
    2019-08-15 2019-09-10相隔: 26
    2019-09-10 2019-10-09相隔: 29
    2019-10-09 2019-10-31相隔: 22
    2019-10-31 2019-11-24相隔: 24
    总相隔: 326 次数: 12
    平均总相隔:27.17
    2019-01-02 2019-01-27相隔: 25
    2019-01-27 2019-02-25相隔: 29
    2019-02-25 2019-03-25相隔: 28
    2019-03-25 2019-04-22相隔: 28
    2019-04-22 2019-05-20相隔: 28
    2019-05-20 2019-06-16相隔: 27
    2019-06-16 2019-07-19相隔: 33
    2019-07-19 2019-08-15相隔: 27
    2019-08-15 2019-09-10相隔: 26
    2019-09-10 2019-10-09相隔: 29
    2019-10-09 2019-10-31相隔: 22
    2019-10-31 2019-11-24相隔: 24
    总相隔: 326 次数: 12
    平均总相隔:27.17
  • 相关阅读:
    完美数据迁移-MongoDB Stream的应用
    补习系列(3)-springboot中的几种scope
    补习系列(2)-springboot mime类型处理
    hdfs directory item limit
    git-format-patch
    SPARK-18560
    hdfs OutOfMemoryError
    hdfs 路径不支持‘:’
    java.io.UTFDataFormatException: encoded string too long:
    scala-maven-plugin excludes
  • 原文地址:https://www.cnblogs.com/jxba/p/11925675.html
Copyright © 2020-2023  润新知