我有三种日期格式:YYYY-MM-DD
, DD.MM.YYYY
, DD/MM/YYYY
。
是否可以验证和解析字符串,如2014-05-18
或18.5.2014
或18/05/2019
?
尝试每种格式,看看是否有效:
from datetime import datetime
def try_parsing_date(text):
for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%Y'):
try:
return datetime.strptime(text, fmt)
except ValueError:
pass
raise ValueError('no valid date format found')
>>> import dateutil.parser
>>> dateutil.parser.parse(date_string)
这应该可以处理Python 2.7+中的大多数标准日期格式。如果你真的有超级自定义日期格式,你总是可以回到Jon Clements提到的那个。
这实际上是我面临的一个问题,我是这样处理它的,我的主要目的是日期分隔符
class InputRequest:
"This class contain all inputs function that will be required in this program. "
def __init__(self, stockTickerName = 'YHOO', stockSite='yahoo', startDate = None,
endDate = datetime.date.today()):
def requestInput(self, requestType =''):
"Fro requesting input from user"
self.__requestInput = input(requestType)
return self.__requestInput
def dateFormat(self, dateType=''):
'''
this function handles user date input
this repeats until the correct format is supplied
dataType: this is the type of date, eg: DOF, Date of Arriveal, etc
'''
while True:
try:
dateString = InputRequest.requestInput(self,dateType)
dtFormat = ('%Y/%m/%d','%Y-%m-%d','%Y.%m.%d','%Y,%m,%d','%Y%m%d') #you can add extra formats needed
for i in dtFormat:
try:
return datetime.datetime.strptime(dateString, i).strftime(i)
except ValueError:
pass
except ValueError:
pass
print('nNo valid date format found. Try again:')
print("Date must be seperated by either [/ - , . ] (eg: 2012/12/31 --> ): ")
为了给@jon- elements这个已经很好的答案添加一点,
为可跟踪性的目的增加了一些异常的详细内容
from datetime import datetime
def try_parsing_date(possible_date, field):
"""
Try to parse a date using several formats, warn about
problematic value if the possible_date does not match
any of the formats tried
"""
for fmt in ('%Y-%m-%d', '%d/%m/%Y', '%m/%d/%Y'):
try:
return datetime.strptime(possible_date, fmt)
except ValueError:
pass
raise ValueError(f"Non-valid date format for field {field}: '{possible_date}'")
这里,possible_date
是可能包含日期的文本格式之一,field
将是您正在测试的变量或列。这样可以更容易地找到有问题的值
纯python:
from datetime import datetime
my_datetime = datetime.strptime('2014-05-18', '%Y-%m-%d')
repr(my_datetime)
>>> 'datetime.datetime(2014,5,18,0,0)'
查看datetime.strptime()格式文档获取更多格式字符串。