这是我目前的代码:
security = input('Security: $')
print ('Date format: YEAR,MO,DA')
s = input('Start date: ')
e = input('End date: ')
start = dt.datetime(s)
end = dt.datetime(e)
df = web.DataReader(security, 'google', start, end)
print (df.tail())
如何正确获取用户日期输入并能够进行转换?我目前运行此代码的错误是:
Traceback (most recent call last):
File "C:\Users\BregmanM\Documents\Python\PDF to Excel\StockPerformance\stockcompetitoranalyis.py", line 17, in <module>
start = dt.datetime(s)
TypeError: an integer is required (got type str)
我理解错误是错误的类型,但我试图让它更有效。我该如何以正确的方式做到这一点?
答案 0 :(得分:1)
我们是这个星球上最不正常的物种。考虑到这一点也可以。日期是邪恶的。如果用户没有输入逗号,我们可以检测到并通知他们。但是,一旦他们这样做了,我们应该能够提供一些支持,假设他们可以获得正确的订单。这是一些尝试并显示其结果的代码。
首先,它查找以逗号分隔的项目,允许随机空格。允许用户输入两个或四个字符的世纪,数字或字符月以及单个或两个字符的数字日。通过从花絮中做出简单的判断,代码构造了一种格式,供import arrow
import re
def process_user_date(user_date):
m = re.match(r'(\d{,4})\s*\,\s*(\w{,8})\s*\,\s*(\d{,2})', user_date)
if not m:
raise ValueError('Need date as year number [comma] month name or number [comma] day number')
print (m.groups())
year_length = len(m.groups()[0])
if not year_length in [2, 4]:
raise ValueError('Year number must be either two or four digits long')
if m.groups()[1].isalpha() and len(m.groups()[1]) < 3:
raise ValueError('Month name must be at least three characters')
month_length = len(m.groups()[1])
if m.groups()[1].isnumeric() and month_length > 2:
raise ValueError('Month number cannot be longer that two characters')
month_length = min(4, month_length)
day_length = len(m.groups()[2])
if not day_length in [1, 2]:
raise ValueError('Day number must be either one or two digits long')
return arrow.get('%s%s%s' % m.groups(), '%s%s%s' % (year_length*'Y', month_length*'M', day_length*'D'))
print (process_user_date('2017 ,November , 7'))
print (process_user_date('2017 ,Nov , 7'))
print (process_user_date('2017 ,November , 07'))
print (process_user_date('2017 ,11 , 07'))
print (process_user_date('17 ,November , 7'))
print (process_user_date('2017 ,11, 7'))
print (process_user_date('17 ,11 , 07'))
库用于获取日期。该库能够以与标准库互换的内部格式提供日期。
('2017', 'November', '7')
2017-11-07T00:00:00+00:00
('2017', 'Nov', '7')
2017-11-07T00:00:00+00:00
('2017', 'November', '07')
2017-11-07T00:00:00+00:00
('2017', '11', '07')
2017-11-07T00:00:00+00:00
('17', 'November', '7')
2017-11-07T00:00:00+00:00
('2017', '11', '7')
2017-11-07T00:00:00+00:00
('17', '11', '07')
2017-11-07T00:00:00+00:00
结果:
{{1}}