How do i convert List into datetime.date object? - python

I'm trying to extract data from my db and display it in a well formatted form.
When db gives me the date i'm trying to display it in the form of String 'Day/Mon/Year'. I have used the following code to do so , but it is throwing me the error.
How do i convert a list to date.time object ?
import psycopg2
from datetime import datetime
db = psycopg2.connect("dbname=news")
if db:
print("DB CONNECTED")
c = db.cursor()
c.execute("select day from (select date(time) as day, count(id) as errors from log where status != '200 OK' group by day order by errors desc limit 1) as seq")
t = c.fetchall()
res = datetime.strftime(t,'%b %d, %Y')
print(res)
db.close()
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'list'

From my experience you need to iterate over the list. maybe this wil work, havent tested it, but thats the way i do it.
import psycopg2
from datetime import datetime
db = psycopg2.connect("dbname=news")
if db:
print("DB CONNECTED")
c = db.cursor()
c.execute("select day from (select date(time) as day, count(id) as errors from log where status != '200 OK' group by day order by errors desc limit 1) as seq")
t = c.fetchall()
c.close()
db.close()
for dates in t:
print(datetime.strftime(dates, '%b %d, %Y'))

Related

Error getting Time from datetime.timedelta object in python

I want to retrieve time in the format of "HH:MM" from datetime.timedelta object. I have a table stored in MySQL database. It has time column, which has stored the time in the format,
00:00:00
I have connected to MySQL server using PyMySQL module,
conn = pymysql.connect("localhost", "root", "cloudera", "streaming")
cursor = conn.cursor()
sql = "select * from table1 limit 5;"
cursor.execute(sql)
row = cursor.fetchone()
row[1]
Output is,
datetime.timedelta(0)
I have been through this post Python: How do I get time from a datetime.timedelta object?. But the difference from that question and mine is in output result. For that post, output is
datetime.timedelta(0, 64800)
And for me it is just,
datetime.timedelta(0)
I just don't get it why the output for me is that way. Can anyone please help me in retrieving time. Thanks in advance.
When you type row[1] python prints the repr of the variable - in this case repr of a timedelta is "datetime.timedetla(days, seconds)".
You can stringify it using str but that would give you HH:MM:SS
str(row[1])
-> "23:00:00"
To get HH:MM you can do the following:
(datetime.min + row[1]).strftime("%H:%M")
-> "23:00"
So your code should look like this:
conn = pymysql.connect("localhost", "root", "cloudera", "streaming")
cursor = conn.cursor()
sql = "select * from table1 limit 5;"
cursor.execute(sql)
row = cursor.fetchone()
timestr = (datetime.min + row[1]).strftime("%H:%M")
print(timestr)

Trying to log date and time into sqlite3

My goal is to take two variables, xdate and xtime and store them into an sqlite database in two separate columns using a python scripts. My code is
from datetime import datetime
import sqlite3 as mydb
import sys
con = mydb.connect('testTime.db')
def logTime():
i=datetime.now()
xdate = i.strftime('%Y-%m-%d')
xtime = i.strftime('%H-%M-%S')
return xdate, xtime
z=logTime()
this is where I get hung up I tried
try:
with con:
cur = con.cursor
cur.execute('INSERT INTO DT(Date, Time) Values (?,?)' (z[0],z[1]))
data = cur.fetchone()
print (data)
con.commit()
except:
with con:
cur=con.cursor()
cur.execute("CREATE TABLE DT(Date, Time)')
cur.commit()
I keep getting none when I try to fetch the data.
Any tips or recommended readings??
You are executing a insert query, it's result is not having any thing to fetch. You should run a select query and then fetch the data.
fetchone()
Fetches the next row of a query result set, returning a single sequence, or None when no more data is available.
An example -
>>> cur.execute('INSERT INTO DT(Date, Time) Values (?,?)', (z[0],z[1]))
<sqlite3.Cursor object at 0x0353DF60>
>>> print cur.fetchone()
None
>>> cur.execute('SELECT Date, Time from DT')
<sqlite3.Cursor object at 0x0353DF60>
>>> print cur.fetchone()
(u'2016-02-25', u'12-46-16')

insert into a mysql database timestamp

I have a part in my python script that I need to insert some data into a table on a mysql database example below:
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2))
db.commit()
db.close()
I have a couple of questions what is incorrect with this syntax and how is possible to change the VALUES to timestamp instead of %s for string? Note the column names in the database are the same as the data stored in the variables in my script.
THanks
try this:
import MySQLdb
import time
import datetime
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="db1")
x = conn.cursor()
try:
x.execute("""INSERT into test (test_date,test1,test2) values(%s,%s,%s)""",(timestamp,test1,test2))
conn.commit()
except:
conn.rollback()
conn.close()
Timestamp creating can be done in one line, no need to use time.time(), just:
from datetime import datetime
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Simply use the database NOW() function, e.g.
timestamp="NOW()"
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2,timestamp))
db.commit()
db.close()

timestamp column in sqlite return string in python

i create a table with SQLite Date Browse App ...
when i want retrieve datetime value from timestamp column , SQLite return unicod type ...
this is my insert code :
def Insert(self,mode,path,vname,stime,ftime):
con = sqlite3.connect(PATH_DataBase) # #UndefinedVariable
con.execute('INSERT INTO SendList VALUES(?,?,?,?,?)',(mode,path,vname,stime,ftime))
con.commit()
con.close()
dt1 = datetime.datetime(2013,01,01,01,01,01,0)
dt2 = datetime.datetime(2015,01,01,01,01,01,0)
c = 0
for f in os.listdir('/home/abbas/test/'):
c += 1
slist.Insert(common.MODE_Bluetooth_JAVA, '/home/abbas/test/'+f,'flower'+str(c) , dt1, dt2)
and now this is my table :
but when i want compare starttime with datetime.now() python give me error :
TypeError: can't compare datetime.datetime to unicode
"SQLite does not have a storage class set aside for storing dates and/or times." Reference: https://www.sqlite.org/datatype3.html
Python's sqlite3 module offers "default adapters for the date and datetime types in the datetime module." Reference: https://docs.python.org/2/library/sqlite3.html#default-adapters-and-converters
The only catch is that you must be sure to define the columns appropriately. Example DDL:
import sqlite3
con = sqlite3.connect(PATH_DataBase, detect_types=sqlite3.PARSE_DECLTYPES)
con.execute('''create table if not exists SendList (
cid primary key,
mode text,
path text,
vname text,
starttime timestamp,
endtime timestamp);''')
con.commit()
con.close()
Any subsequent connections to insert or select data must pass sqlite3.PARSE_DECLTYPES as the value for the keyword argument (aka kwarg) detect_types. Example:
import datetime as dt
con = sqlite3.connect(PATH_DataBase, detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute('''select
*
from
SendList
where
starttime between ? and ?
limit 10;''',
(dt.datetime(2013,1,1,0,0,0), dt.datetime(2014,12,31,23,59,59)))
results = cur.fetchall()

python still can't insert into database

i want insert my data to my MySQL database but still can't, here is my code:
import ue9
d = ue9.UE9()
import datetime
from time import gmtime, strftime
import MySQLdb
timee = "%Y-%m-%d %H:%M:%S"
noww = strftime(timee, gmtime())
print noww
db = MySQLdb.connect("localhost","root","root","temperature")
cursor = db.cursor()
sql = ("INSERT INTO Mydate(datenow) VALUES(%s)",(noww))
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
but still can't connect to database can anyone help me ?
You miss a comma in the list of values:
sql = ("INSERT INTO Mydate(datenow) VALUES(%s)",(noww,))

Categories