我有三种日期格式:YYYY-MM-DD
,DD.MM.YYYY
,DD/MM/YYYY
。
是否可以验证和解析2014-05-18
或18.5.2014
或18/05/2019
等字符串?
答案 0 :(得分:75)
尝试每种格式并查看其是否有效:
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')
答案 1 :(得分:12)
>>> import dateutil.parser
>>> dateutil.parser.parse(date_string)
这应该处理Python 2.7+中的大多数标准日期格式。如果你真的有超级自定义日期格式,你可以随时回到Jon Clements提到的那个。
答案 2 :(得分:0)
Pure 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()格式文档以获取更多格式字符串。
答案 3 :(得分:0)
这实际上是我面临的一个问题,这是我如何接近它,我的主要目的是日期分隔符
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 --> ): ")