來源:https://www.cnblogs.com/dplearning/p/5737966.htmlhtml
用time模塊的strptime函數獲取時間元組,若是成功爲合法時間,反之爲非法時間python
1 def isVaildDate(self, date): 2 try: 3 if ":" in date: 4 time.strptime(date, "%Y-%m-%d %H:%M:%S") 5 else: 6 time.strptime(date, "%Y-%m-%d") 7 return True 8 except: 9 return False
Python time strptime() 函數根據指定的格式把一個時間字符串解析爲時間元組。函數
strptime()方法語法:spa
time.strptime(string[, format])
返回struct_time對象。code
python中時間日期格式化符號:orm
如下實例展現了 strptime() 函數的使用方法:htm
1 #!/usr/bin/python 2 import time 3 4 struct_time = time.strptime("30 Nov 00", "%d %b %y") 5 print(type(struct_time)) 6 print("returned tuple: %s " %(str(struct_time))) 7 8 #<class 'time.struct_time'> 9 #returned tuple: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
1 print(time.strptime("2018-05-02 12:23:34","%Y-%m-%d %H:%M:%S")) 2 3 #time.struct_time(tm_year=2018, tm_mon=5, tm_mday=2, tm_hour=12, tm_min=23, tm_sec=34, tm_wday=2, tm_yday=122, tm_isdst=-1)