我希望能够只输入一系列日期而不是每一个日期,因为我想对这些数据做一些时间序列工作。到目前为止,这是我的代码:
import re
def date():
dates = []
user_input =''
pattern = re.compile('\d{2}.\d{2}.\d{2}')
while user_input != 'end':
user_input =raw_input("Please put folder with format yy.mm.dd or 'end': ")
if pattern.match(user_input):
dates.append(user_input)
elif user_input == 'end':
print 'Dates:'
else:
print "Use yy.mm.dd format or write 'end'"
return dates
答案 0 :(得分:2)
如果你想使用日期,我会建议你使用datetime,因为你的正则表达式会匹配dd.dd.dd的任何组合:
from datetime import datetime
def date():
dates = []
user_input =''
while user_input != 'end':
user_input = raw_input("Please put folder with format yy.mm.dd or 'end': ")
try:
dte = datetime.strptime(user_input,"%y.%m.%d")
dates.append(dte)
except ValueError:
print "Use yy.mm.dd format or write 'end'"
print 'Dates:'
return dates
如果您想要开始和结束之间的日期范围:
from datetime import datetime, timedelta
def date():
dates = []
while True:
start = raw_input("Please put start date with format yy.mm.dd or 'end': ")
if start == "end":
break
end = raw_input("Please put end date with format yy.mm.dd or 'end': ")
try:
start = datetime.strptime(start,"%y.%m.%d")
end = datetime.strptime(end,"%y.%m.%d")
for _ in xrange((end-start).days+1):
dates.append(start)
start += timedelta(days=1)
except ValueError:
print "Use yy.mm.dd format or write 'end'"
print 'Dates:'
return dates
pandas也可能有用:
from datetime import datetime
import pandas as pd
def date():
dates = []
while True:
start = raw_input("Please put start date with format yy.mm.dd or 'end': ")
if start == "end":
break
end = raw_input("Please put end date with format yy.mm.dd or 'end': ")
try:
start = datetime.strptime(start,"%y.%m.%d")
end = datetime.strptime(end,"%y.%m.%d")
dates.append(pd.date_range(start, end))
except ValueError:
print "Use yy.mm.dd format or write 'end'"
print 'Dates:'
return dates