I have a python code which gets following two parameters: AMAZON.DATE and AMAZON.TIME (format definition here):
import pymysql
def func(date, start_time):
conn = pymysql.connect(hostname, user=username,
passwd=password, db=database, connect_timeout=5)
cur = conn.cursor()
# SQL statement here
Now what I want to do is join these two date and time types and insert them as a sql DATETIME type. So the insert statement should be like - INSERT INTO table1 VALUES (date_time);. What I am having difficulty in is joining the two Amazon types and forming sql DATETIME type. How can I do that?
I would suggest you to convert AMAZON.DATE and AMAZON.TIME into datetime objects and then simply use
datetime.datetime.combine(datetime.date(2011, 01, 01), datetime.time(10, 23))
For example -
import datetime
date_object = datetime.datetime.strptime('2015-06-07T', '%Y-%M-%dT').date()
time_object = datetime.datetime.strptime('04:00','%H:%M').time()
date_obj_final = datetime.datetime.combine(date_object, time_object)
#output
2015-01-07
04:00:00
2015-01-07 04:00:00
Let me know,if it works !
Related
Im trying to query a table, and need to grab all products that have a date = today date.
Below is my code so far
import sqlite3
from datetime import date
date = date.today()
con = sqlite3.connect('test.db')
cur = con.cursor()
date = date.today()
sql_q = f'''SELECT date, name FROM table WHERE date = {date}'''
table = cur.execute(sql_q)
for row in table:
print(row)
i am using an SQlite 3 db and all data has been entered with the following format:
2022-09-20
However this variable type does not seem to work with SQL.
i know the SQL code should look somthing like this
SELECT name FROM test WHERE date = '2022-09-20'
but i'd like the date to be selected automatically from python rather than typing it in manually.
Use the function date() to get the current date:
SELECT name FROM test WHERE date = date()
or CURRENT_DATE:
SELECT name FROM test WHERE date = CURRENT_DATE
I think you need to convert date to string and then pass it in query.
maybe your datatype of column and date.today() is different.
date = date.strftime('%Y-%m-%d')
try using this.
I am trying to insert date and time into a sqlite table.
Here is my code.
import sqlite3
from datetime import datetime
### Date Time ###
dt = datetime.now()
dates = dt.date()
times = dt.time()
def sql(date, time):
### CREATE DB
con = sqlite3.connect("date.db")
cur = con.cursor()
## CREATE TABLE
cur.execute("CREATE TABLE if NOT EXISTS d_t (datee, timee)")
con.commit()
## INSERT DATA
cur.execute("INSERT INTO d_t (datee, timee) VALUES (?,?)", (date, time))
con.commit()
## VIEW DATA
cur.execute("SELECT * from d_t")
row = cur.fetchall()
print(type((row[0][0]))) # Printing_Date_only
sql(dates, times)
But this is the error I am getting:
Traceback (most recent call last):
File "C:\Users\Hridoy\Documents\GitHub\Covid19\datedb.py", line 26, in <module>
sql(dates, times)
File "C:\Users\Hridoy\Documents\GitHub\Covid19\datedb.py", line 18, in sql
cur.execute("INSERT INTO d_t (datee, timee) VALUES (?,?)", (date, time))
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
I don't want to insert the date and time as strings because I need to compare two dates later, and one of them will come from the database.
Kindly looking for solution of this.
Working with SQLite can be a little tricky when trying to store dates/times, and I don't think you can store a time (without a date). Why not just store the date and time together as the complete datetime value?
The below code stores the datetime value and modifies the sqlite3.connect() call to make dealing with datetimes nicer (we'll get a datetime back when we query the database). We also need to specify the type of the d_t table's "date_time" column as a SQLite timestamp when we create the table.
import sqlite3
from datetime import datetime
### Date Time ###
dt = datetime.now()
def sql(dt_value):
### CREATE DB
con = sqlite3.connect("date.db", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
## CREATE TABLE
cur.execute("CREATE TABLE if NOT EXISTS d_t (date_time timestamp)")
con.commit()
## INSERT DATA
cur.execute("INSERT INTO d_t (date_time) VALUES (?)", (dt_value,))
con.commit()
## VIEW DATA
cur.execute("SELECT * from d_t")
row = cur.fetchall()
print(type(row[0][0])) # Print type of datetime
print(row[0][0]) # Print datetime
print(row[0][0].date()) # Print date
print(row[0][0].time()) # Print time
sql(dt)
As an alternative solution, you may also want to try the "easy_db" library I wrote to help out with this kind of problem. Just install it with pip:
pip install easy_db
Then we can accomplish the same task with less/cleaner code.
import easy_db
from datetime import datetime
### Date Time ###
dt = datetime.now()
def insert_and_read_datetime(dt_value):
# Create and connect to SQLite database
db = easy_db.DataBase("date.db")
# Create "d_t" table and add one row of data to it
# From our input dictionary, a "date" column is automatically created and
# this column is given the SQLite timestamp type based on the type of dt_value
db.append("d_t", {"date": dt_value})
# Run a SELECT * query to pull the full "d_t" table
# Returned data is a list with a dictionary for each row
data = db.pull("d_t")
print(type(data[0]["date"])) # Print type of datetime
print(data[0]["date"]) # Print datetime
print(data[0]["date"].date()) # Print date
print(data[0]["date"].time()) # Print time
insert_and_read_datetime(dt)
Best of luck with your Covid-19 project!
I am using Python to connect to SQL Server database and execute several 'select' type of queries that contain date range written in a particular way. All these queries have the same date range, so instead of hard-coding it, I'd prefer to have it as a string and change it in one place only when needed.
So far, I found out that I can use datetime module and the following logic to convert dates to strings:
from datetime import datetime
start_date = datetime(2020,1,1).strftime("%Y-%m-%d")
end_date = datetime(2020,1,31).strftime("%Y-%m-%d")
Example of the query:
select * from where xxx='yyy' and time between start_date and end_date
How can I make it work?
EDIT
my code:
import pyodbc
import sqlalchemy
from sqlalchemy import create_engine
from datetime import datetime
start_date = datetime(2020,1,1).strftime("%Y-%m-%d")
end_date = datetime(2020,1,31).strftime("%Y-%m-%d")
engine = create_engine("mssql+pyodbc://user:pwd#server/monitor2?driver=SQL+Server+Native+Client+11.0")
sql_query = """ SELECT TOP 1000
[mtime]
,[avgvalue]
FROM [monitor2].[dbo].[t_statistics_agg]
where place = 'Europe' and mtime between 'start_date' and 'end_date'
order by [mtime] asc;"""
df = pd.read_sql(sql_query, engine)
print(df)
Thank you all for your input, I have found the answer to make the query work. The variables should look like:
start_date = date(2020, 1, 1)
end_date = date(2020, 1, 31)
and SQL query like:
sql_query = f""" SELECT TOP 1000
[mtime]
,[avgvalue]
FROM [monitor2].[dbo].[t_statistics_agg]
where place = 'Europe' and mtime between '{start_date}' and '{end_date}'
order by [mtime] asc;"""
I got a python script, which is supposed to fetch data of my mysql table (contains a date) and then it should print out the amount of days between today´s date and the date of my mysql table.
I already tried substracting the two dates, but this wouldn´t work. So I tried substracting today´s date and my birthday, which worked. So I think the problem is the mysql date.
import datetime
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database='appointments'
)
eventDate = mydb.cursor()
eventDate.execute('SELECT event_date FROM appointdatetitle')
Date = eventDate.fetchall()
tdelta = datetime.timedelta(days=7)
today = datetime.date.today()
eday = Date
till_eday = eday - today
print(till_eday.days)
Date = eventDate.fetchall() fetchall actually fetches a tuple of tuples
e.g.
(('abcd',), ('efgh',))
You would want to get the Date by looping over the list and getting the elements. e.g.
for d in Date:
#This will contain the date you need
print(d[0])
Or you can directly access an element by doing say Date[0][0]
After update from OP, this is what can be done!
OP can use https://dateutil.readthedocs.io/en/stable/index.html to use the
from dateutil.relativedelta import * to increment the month!
import datetime
from dateutil.relativedelta import *
Date = [(datetime.date(2019, 4, 24),)]
#Extract actual datetime object from Date variable
date_obj = Date[0][0]
#Increment month by 1 since January starts from 0
date_obj += relativedelta(months=1)
today = datetime.date.today()
#Using datetime from above
eday = date_obj
till_eday = eday - today
print(till_eday.days)
The output will be 23
Below code works perfectly:
import pypyodbc
import datetime
connection = pypyodbc.connect('Driver={SQL Server};'
'Server=some_server;'
'Database=some_db')
cur = connection.cursor()
some_time = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
query = "insert into table_a (date_created) values ('"+some_time+"')"
cur.execute(query)
connection.commit()
connection.close()
But if I change (adding microseconds to date)
some_time = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
it generates error:
DataError: ('22007', '[22007] [Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/or time from character string.')
date_created column is of datetime type and does display microseconds.
Any thoughts?
SQL Server datetime columns are only able to store fractional seconds to millisecond precision (3 decimal places). When you do
some_time = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
you get a string formatted to the precision of Python's datetime, which is microseconds (6 decimal places)
>>> some_time
'2018-09-28 16:38:14.344801'
and SQL server doesn't like the extra three decimal places.
The solution is to not format the datetime as a string, just pass the datetime value itself in a proper parameterized query
query = "insert into table_a (date_created) values (?)"
params = (datetime.datetime.utcnow(), )
cur.execute(query, params)