代码
from datetime import date,time,datetime #time类 """time类由hour小时、minute分钟、second秒、microsecond毫秒和tzinfo五部分组成 time([hour, minute, second, microsecond, tzinfo]) """ a = time(hour=8, minute=18, second=28, microsecond=380) b = time(hour=18, minute=28, second=38, microsecond=480) print ("时间为:",a,"获取该时间的时、分、秒、微秒,如下:") #08:18:28.000380 print("小时\t(a.hour):",a.hour,"\t(a.__getattribute__('hour')):",a.__getattribute__('hour')) print("小时\t(a.second):",a.second,"\t(a.__getattribute__('second')):",a.__getattribute__('second')) print("小时\t(a.microsecond):",a.microsecond,"\t(a.__getattribute__('microsecond')):",a.__getattribute__('microsecond')) """用于时间比较大小的方法: 方法名 方法说明 用法 __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) """ 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.strftime("%H:%M:%S")) #08:18:28按指定格式输出时间 print(a.isoformat()) #08:18:28.000380 print(a.__str__()) #08:18:28.000380 #combine(…):将一个date对象和一个time对象合并生成一个datetime对象 datea = date(2019,11,25) timea = a datetimea = datetime.combine(datea,timea) print (datetimea) #2019-11-25 08:18:28.000380 #__nonzero__() 判断时间是否非零 #print(a.__nonzero__()) #报错,未解决AttributeError: 'datetime.time' object has no attribute '__nonzero__' """ 常见错误: 问题:TypeError: 'module' object is not callable 原内容: import time time2 = time(hour=8, minute=00, second=00, microsecond=0) print (time2) 原因:导入的模块错误,应为:from datetime import time 修改后内容: from datetime import time time2 = time(hour=8, minute=00, second=00, microsecond=0) print (time2) """
结果
时间为: 08:18:28.000380 获取该时间的时、分、秒、微秒,如下: 小时 (a.hour): 8 (a.__getattribute__('hour')): 8 小时 (a.second): 28 (a.__getattribute__('second')): 28 小时 (a.microsecond): 380 (a.__getattribute__('microsecond')): 380 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 08:18:28 08:18:28.000380 08:18:28.000380 2019-11-25 08:18:28.000380