python之当前标准时间显示
借编程金典的python标准时间类稍稍修改,显示当前标准时间
#simple definition of class Time.
#coding:utf-8
import time
class Time1:
def __init__(self):
#'''Intitializes hour,minute and second to zero'''
self.hour = int(((time.ctime()).split(' ',5)[4]).split(':', 3)[0]) #0-23
self.minute = int(((time.ctime()).split(' ',5)[4]).split(':', 3)[1]) # 0-59
self.second = int(((time.ctime()).split(' ',5)[4]).split(':', 3)[2])# 0-59
def setTime(self, hour, minute, second):
'''set values of hour,minute, and second'''
self.setHour(hour)
self.setMinute(minute)
self.setSecond(second)
def setHour(self, hour):
'''set hour value'''
if 0 <= hour < 24:
self.hour = hour
else:
print('Invalid hour value: %d' % hour)
def setMinute(self, minute):
'''set minute value'''
if 0 <= minute < 60:
self.minute = minute
else:
print('Invalid minute value: %d' % minute)
def setSecond(self, second):
if 0 <= second < 60:
self.minute = second
else:
print('Invalid second value: %d' % second)
def getHour(self):
'''Get hour value'''
return self._hour
def getMinute(self):
'''get minute value'''
return self._minute
def getSecond(self):
'''get second value'''
return self.second
def printMilitary(self):
#Prints object of class Time in military format
print('%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second))
def printStandard(self):
#print object of class time in standard fromat
standardTime = ''
if self.hour == 0 or self.hour == 12:
standardTime += '12:'
else:
standardTime += '%d:' % (self.hour % 12)
standardTime += "%.2d:%.2d" % (self.minute, self.second)
if self.hour < 12:
standardTime += " AM"
else:
standardTime += " PM"
print(standardTime)
t = Time1()
t.printStandard()
print(Time1.__name__)
显示如下
5:18:25 PM
END!