你總是可以分析文本,然後用它來構建一個日期時間你自己 - 或者預先驗證它是否適合你:
from datetime import datetime
def to_datetime(date_string):
year = int(date_string[0:4])
month = int(date_string[5:7])
day = int(date_string[8:10])
return datetime(year, month, day)
print(to_datetime('2015-13-23 13:42:13'))
拋出:
Traceback (most recent call last):
File "test.py", line 11, in <module>
print(to_datetime('2015-13-23 13:42:13'))
File "test.py", line 9, in to_datetime
return datetime(year, month, day)
ValueError: month must be in 1..12
如果你想知道如何datetime
它 - 使用源,盧克!
>>> import datetime
>>> datetime.__file__
'/usr/lib/python3.5/datetime.py'
打開該文件,你會發現:
def _check_date_fields(year, month, day):
year = _check_int_field(year)
month = _check_int_field(month)
day = _check_int_field(day)
if not MINYEAR <= year <= MAXYEAR:
raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
if not 1 <= month <= 12:
raise ValueError('month must be in 1..12', month)
dim = _days_in_month(year, month)
if not 1 <= day <= dim:
raise ValueError('day must be in 1..%d' % dim, day)
return year, month, day
最常見的方式取得錯誤是交換月份和日期,因爲美國和歐洲的習俗是相反的,所以誤差是有道理的。 –
你爲什麼在第13個月過世? – NotAnAmbiTurner
不知道這是否是正確的方式,但可能是你可以引發異常和異常阻止 –