我试图想出一种方法来以尽可能最好的pythonic方式来实现这一点。现在我能想到的唯一方法就是强行推行它。Python,日期验证
用户输入以下列方式中的一个的日期(通过命令行)(来自./mypy.py日期=“20110909.00 23”)
date='20110909'
date='20110909.00 23'
date='20110909.00 20110909.23'
所有三个实施例应具有相同的结果,如果它填充一个列表(我可以排序),如
['20110909.00', '20110909.23]
,甚至两个独立的排序变量,但在所有情况下,它的YYYYMMDD.HH,并且需要确保它确实是一个没关系日期而不是文字。
任何想法?
谢谢。
+++++编辑+++++ 插上这个之后,我想我需要先做很多日期检查/操作。这似乎都很好。除了最后我通过日期验证运行列表,并且每次都失败 - 即使它应该通过。
./test.py日期(I与启动它)= '20110909.00 23'
(或日期的任何变化 - 即日期= '20 22' 或日期= '20110909' 或日期=” 20110909.00 23' 等)
import sys, re, time, datetime
now = datetime.datetime.now()
tempdate=[]
strfirstdate=None
strtempdate=None
temparg2 = sys.argv
del temparg2[0]
tempdate = temparg2[0].replace('date=','')
date = tempdate.split(' ');
tempdate=[]
date.sort(key=len, reverse=True)
result = None
# If no date is passed then create list according to [YYMMDD.HH, YYMMDD.HH]
if date[0] == 'None':
tempdate.extend([now.strftime('%Y%m%d.00'), now.strftime('%Y%m%d.%H')])
# If length of date list is 1 than see if it is YYMMDD only or HH only, and create list according to [YYMMDD.HH, YYMMDD.HH]
elif len(date) == 1:
if len(date[0]) == 8:
tempdate.extend([ date[0] + '.00', date[0] + '.23'])
elif len(date[0]) == 2:
tempdate.extend([now.strftime('%Y%m%d') + '.' + date[0], now.strftime('%Y%m%d') + '.' + date[0]])
else:
tempdate.extend([date[0], date[0]])
# iterate through list, see if value is YYMMDD only or HH only or YYYYMMDD.HH, and create list accoring to [YYYYMMDD.HH, YYYYMMDD.HH] - maximum of 2 values
else:
for _ in range(2):
if len(date[_]) == 8:
strfirstdate = date[0]
tempdate.append([ date[_] + '.00'])
elif len(date[_]) == 2:
if _ == 0: # both values passed could be hours only
tempdate.append(now.strftime('%Y%m%d') + '.' + date[_])
else: # we must be at the 2nd value passed.
if strfirstdate == None:
tempdate.append(now.strftime('%Y%m%d') + '.' + date[_])
else:
tempdate.append(strfirstdate + '.' + date [_])
else:
strfirstdate = date[0][:8]
tempdate.append(date[_])
tempdate.sort()
for s in tempdate:
try:
result = datetime.datetime.strptime(s, '%Y%m%d.%H')
except:
pass
if result is None:
print 'Malformed date.'
else:
print 'Date is fine.'
print tempdate
++++编辑2 ++++ 如果删除所述底部部分(tempdate.sort后())和与此替换它。
strfirstdate = re.compile(r'([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]+\.[0-9][0-9])')
for s in tempdate:
if re.match(strfirstdate, s):
result = "validated"
else:
print "#####################"
print "#####################"
print "## error in date ##"
print "#####################"
print "#####################"
exit
它会适当地验证。
这整个方法似乎不是非常pythonic。
你的意思是用蛮力?显然你必须执行一些逻辑来分离你显示的不同情况。只要做到这一点,展示你的代码,我们将帮助你使它变得更加pythonic。 – Achim
@Achim我已经开始做了该项目的长度先看看,如果是2比对验证数长。如果不是,则对照正则表达式'thedate = re.compile(r'([0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0- 9] [0-9] + \。[0-9] [0-9])') if re.match(thedate,item): print“validated” ...' – Chasester