I am attempting to insert data from a dictionary into a database. I want to iterate over the values and format them accordingly, depending on the data type. Here is a snippet of the code I am using:
def _db_inserts(dbinfo):
try:
rows = dbinfo["datarows"]
for row in rows:
field_names = ";".join([""{0}"".format(x) for x in row.keys()])
value_list = row.values()
for pos, value in enumerate(value_list):
if isinstance(value, str):
value_list[pos] = ""{0}"".format(value)
elif isinstance(value, datetime):
value_list[pos] = ""{0}"".format(value.strftime("%Y-%m-%d"))
values = ";".join(value_list)
sql = "INSERT INTO table_foobar ({0}) VALUES ({1})".format(field_names, values)
except Exception as e:
print "BARFED with msg:",e
When I run the algo using some sample data (see below), I get the error:
TypeError: sequence item 0: expected string, int found
An example of a value_list data which gives the above error is:
value_list = [377, -99999, -99999, "f", -99999, -99999, -99999, 1108.0999999999999, 0, "f", -99999, 0, "f", -99999, "f", -99999, 1108.0999999999999, -99999, "f", -99999, "f", -99999, "f", "f", 0, 1108.0999999999999, -99999, -99999, "f", "f", "f", -99999, "f", "1984-04-02", -99999, "f", -99999, "f", 1108.0999999999999]
What am I doing wrong?
How do I calculate the date six months from the current date using the datetime Python module?
1 answers
I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a review date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data.
Answer #1
I found this solution to be good. (This uses the python-dateutil extension)
from datetime import date
from dateutil.relativedelta import relativedelta
six_months = date.today() + relativedelta(months=+6)
The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)
$ date(2010,12,31)+relativedelta(months=+1)
datetime.date(2011, 1, 31)
$ date(2010,12,31)+relativedelta(months=+2)
datetime.date(2011, 2, 28)