i have wrote a simple script to get inputs from user and store it in the database.
I also want date input but some problems are arising.
First I have used datetime.date() function and passing the date but it is throwing some error.
I don't understand why?
import pyodbc
import datetime
class data:
def __init__(self):
self.name=raw_input( "Enter Name: ")
self.section=raw_input( "Enter section: ")
self.eon=datetime.date(1943,3, 13) # This is in the requested 'YYYY-MM-DD' format.
a=data()
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=KIRAN-PC;DATABASE=testing')
cursor = cnxn.cursor()
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (?,?,?)",(a.name,a.section,a.eon))
cnxn.commit()
Error:
Enter Name: Tim
Enter section: A
Traceback (most recent call last):
File "C:/Python33/data2.py", line 15, in <module>
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (?,?,?)",(a.name,a.section,a.eon))
Error: ('HYC00', '[HYC00] [Microsoft][ODBC SQL Server Driver]Optional feature not implemented (0) (SQLBindParameter)')
Change the import from from datetime import datetime to import datetime. With your current code you import the class datetime from the module datetime and call the date method from this class with wrong parameters. But you want to call the constructor of the date class in the datetime module.
Update to answer your edit
According to https://code.google.com/p/pyodbc/issues/detail?id=204:
On Windows, you need to use DRIVER={SQL Server Native Client 10.0} for a driver that understands the ODBC date type.
Your current driver SQL Server does not understand how to pass the date datatype to your database.
You also have to pay attention that in your database the column Enrol_On is of type SQL_TYPE_DATE. See https://code.google.com/p/pyodbc/wiki/DataTypes for the mapping of python datatypes to SQL types.
Related
Hi i am creating ics file for calendar invitation, as far as i see that if i dont put time zone some emails may become conflict, i have checked working ics files from zoom and i see that they put
BEGIN:VTIMEZONE
TZID:Turkey Standard Time
BEGIN:STANDARD
DTSTART:16010101T000000
TZOFFSETFROM:+0300
TZOFFSETTO:+0300
END:STANDARD
END:VTIMEZONE
now i translated this to code like
timezone = Timezone()
timezone.add('TZID','Turkey Standard Time')
timezoneStandard = TimezoneStandard()
timezoneStandard.add('TZOFFSETFROM', timedelta(hours=3))
timezoneStandard.add('TZOFFSETTO', timedelta(hours=3))
timezoneStandard.add('DTSTART','16010101T000000') <==== PROBLEM IS HERE
timezone.add_component(timezoneStandard)
cal.add_component(timezone)
But i dont know to translate 16010101T000000 , i am getting error You must use datetime, date, timedelta
This is ISO-8601, you can parse this for example with .isoparse [readthedocs] from the dateutil package [readthedocs].
You can install this, for example in your local environment with:
pip3 install dateutils
Then you can parse this with:
>>> from dateutil.parser import isoparse
>>> isoparse('16010101T000000')
datetime.datetime(1601, 1, 1, 0, 0)
So you can use this in your code with:
timezoneStandard.add('DTSTART', isoparse('16010101T000000'))
I have a spider that will run on schedule. Spider input is based on Date. From date of last scrape to todays date. So the question is how to save the date of last scrape within the Scrapy project? There is an option to get data from scrapy settings using pkjutil module, but i did not find any reference in the docs on how to write data in that file. Any idea? Maybe an alternative?
P.S. My other option is to use some free remote MySql DB just for this. But looks like more work if simple solution is available.
import pkgutil
class CodeSpider(scrapy.Spider):
name = "code"
allowed_domains = ["google.com.au"]
def start_requests(self):
f = pkgutil.get_data("au_go", "res/state.json")
ids = json.loads(f)
id = ids[0]['state']
yield {'state':id}
ids[0]['state'] = 'New State'
with open('./au_go/res/state.json', 'w') as f:
json.dump(ids, f)
The above solution works fine when ran locally. But I am getting no such file or directory when running the code at Scrapinghub.
File "/tmp/unpacked-eggs/__main__.egg/au_go/spiders/test_state.py", line 33, in parse
with open(savePath, 'w') as f:
IOError: [Errno 2] No such file or directory: './au_go/res/state.json'
The problem is fixed with use of Scrapinghub Colections
And scrapinghub API. Works nice now.
Here is an example code in case somebody will find it usefull.
from scrapinghub import ScrapinghubClient
client = ScrapinghubClient(Your API KEY)
project = client.get_project(Your Project ID)
collections = project.collections
last_accessed = collections.get_store('last_accessed')
last_accessed.set({'_key': 'Date', 'value': '12-54-1235'})
print last_accessed.get('Date')['value']
Here is my code
from pandas import read_csv
from pandas.tools.plotting import scatter_matrix
from matplotlib import pyplot
filename = 'iris.data.csv'
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = read_csv(filename, names=names)
print(dataset.shape)
print(dataset.head(20))
# Data visualizations
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
pyplot.show()
When i run above code. Then following error is shown
Traceback (most recent call last):
File "/media/k/UBUNTU2/Work and stuff/coding language/Python/Machine learning/exp.py", line 43, in <module>
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
File "/usr/local/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 2090, in plot_frame
raise ValueError('Invalid chart type given %s' % kind)
ValueError: Invalid chart type given box
Any idea ? What should i do? Please help
Your pandas version (0.14) is already 3 years old. The "box" kind was introduced in version 0.15. Now we are at version 0.20.
The solution is thus to install a newer version of pandas in order to be able to use kind="box" in the plotting wrapper.
If you need to use version 0.14 you can get boxplot using the DataFrame.boxplot() method. The usage according to documentation would be:
df = DataFrame(rand(10,5))
plt.figure();
bp = df.boxplot()
Fairly new to coding and have been browsing this site for a while, not clued up enough to give anything back yet though.
I'm trying to calculate the Hurst exponent using this code originally from QuantStart but modified to import data from Yahoo. Daily Hurst Exponent
When running in Powershell I return these errors:
C:\Program Files\Anaconda2\lib\site-packages\pandas\io\data.py:35: FutureWarning:
The pandas.io.data module is moved to a separate package (pandas-datareader) and will be removed from pandas in a future
version.
After installing the pandas-datareader package (https://github.com/pydata/pandas-datareader), you can change the import
from pandas.io import data, wb to from pandas_datareader import data, wb.
FutureWarning)
When changing from pandas.io import data, wb to from pandas_datareader import data, wb:
Traceback (most recent call last):
File "hurst.py", line 23, in
aapl = DataReader("AAPL", "yahoo", datetime(2012,1,1), datetime(2015,9,18))
NameError: name 'DataReader' is not defined
Please can someone help and guide me in what changes I'm missing to get the script to run properly.
Thanks,
James
from pandas_datareader.data import DataReader
...
ts1 = DataReader(symbol, "yahoo", start_date, end_date)
See the usage in the documentation
for pandas datareader:
from pandas_datareader import data
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
f = data.DataReader("F", 'yahoo', start, end)
I'm trying to implement simple_tokenize using dictionary as the output from my previous code but i get an error message. Any assistance with the following code would be much appreciated. I'm using Python 2.7 Jupyter
import csv
reader = csv.reader(open('data.csv'))
dictionary = {}
for row in reader:
key = row[0]
dictionary[key] = row[1:]
print dictionary
The above works pretty well but issue is with the following:
import re
words = dictionary
split_regex = r'\W+'
def simple_tokenize(string):
for i in rows:
word = words.split
#pass
print word
I get this error:
NameError Traceback (most recent call last)
<ipython-input-2-0d0e05fb1556> in <module>()
1 import re
2
----> 3 words = dictionary
4 split_regex = r'\W+'
5
NameError: name 'dictionary' is not defined
Variables are not saved between Jupyter sessions, unless you explicitly do so yourself. Thus, if you ran the first code section, then quit your Jupyter session, started a new Jupyter session and ran the second code block, dictionary is not preserved from the first session and will thus be undefined, as indicated by the error.
If you run the above code blocks differently (e.g., not across Jupyter sessions), you should indicate this, but the tags and traceback suggest this is what you do.