How To add datetime into sql by python - python

I am working on a raspberry project which adds variables into a sqlite database
curs.execute("INSERT INTO EntryLog(EntryTime)VALUES(?)",(time)
to make this work how can I make put current datetime value into time? (EntryTime is DATETIME value in sql, I need date and time in the same column)

You need to format time as string in format Y-m-d like time.strftime('%Y-%m-%d')
from datetime import datetime
time=datetime.now()
curs.execute("INSERT INTO EntryLog(EntryTime)VALUES(?)",(time.strftime('%Y-%m-%d'))

Related

Python and SQL timezones

I'm using python to create a datetime value with Europe/London timezone:
import datetime
from pytz import timezone, utc
now_utc = datetime.datetime.now()
now_uk = now_utc.astimezone(timezone('Europe/London')) # convert to local time
I then want to add this value to a SQL database using sqlite3 within python.
cursor = con.cursor()
sql_data = ("INSERT INTO TCADATA (datetime, gym1) VALUES (datetime(:datetime), :gym1;")
cursor.execute(sql_data, {"datetime":now_uk, "gym1":data["gym1"]})
The value that gets added to the SQL database is one hour different from my London timezone, so if it's 16:00 here, the value in the database is 15:00.
My guess is that SQLite3 is converting the datetime to UTC.
How do I specify to sqlite that the value is a London time zone? I would prefer to specify London like I have done with python, rather than GMT since this changes at daylight savings.
Or perhaps it would be simpler to keep it as UTC and convert it to London time when the data is read?
I think the best way to get round this issue is to either store the datetimes in UTC timezone on the server and convert to local time zones as needed when retrieving the data in python.

Converting local time to Zulu time in order to compare times

I have a DB with time entries formatted as follow:
2018-11-05T08:58:00Z
I'm trying to generate SQL queries to compare "now()" with the time in the DB to determine which row(s) to return.
I'm battling to "convert" my local time (now()) to an equivalent time format so that I can use < or > operations against the DB values.
Additionally, I am not sure if the problem has two parts. The example fo the time above is not in a "Datetime" field in MySQL but stored simply as TEXT, leaving me to suspect that I would need to "convert" the DB entries into another format first?
The following code, using the datetime module, works for me (tested in Python 3.6):
import datetime
value = "2018-11-05T08:58:00Z"
dt = datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
# Result is: datetime.datetime(2018, 11, 5, 8, 58)
This will convert your string values to datetime instances, which you can then compare to now(). The values that get created should be naive (meaning they have no associated timezone information).
However, if you are sure that now() for you is not UTC (aka Zulu time), you may need to do a conversion. This could be possible if, for example, you are using Django's timezone.now() and your configured timezone is something other than UTC. In this case, I might convert the result of now() to UTC, so you only have to convert one value. The pytz module can easily handle this kind of thing.
Check this :
import time
time = time.strftime('%Y-%m-%dT%H:%M:%SZ')
print(time)

How to convert pandas Timedelta into datetime?

I have a python dataframe.One of its column is like Timedelta('0 days 09:35:00').If I save it into mysql, the time is changed to 34500000000000.
How can I properly save the time into mysql?
First, you need to define an appropriate format to store your timdelta object in mysql. The reason is that the timedelta format type does not exists in mysql as far as I'm aware. For example, if you want to convert the timedelta object in seconds or days as float:
timedelta.total_seconds()
timedelta.days
If you want to convert the timedelta to string:
str(timedelta)

Convert date format to insert into mysql db

I have pandas column row['date'] which contains date in format 11/05/2015. I am trying to insert it into mysql db but having problems due to incorrect format of date field data. It has to be converted into 2015-11-05 in order to be inserted. Without storing the new value in variable how can I convert the date into required format?
Current format: 11/05/2015
Required format: 2015-11-05
Is the current format mm/dd/yyyy? If so
from datetime import datetime
row['date'] = datetime.strptime(row['date'], '%m/%d/%Y').strftime('%Y-%m-%d')
Use dateutil.parser,
This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time.
Here is a MWE.
from dateutil.parser import parse
current_date = '11/05/2015'
required_date = parse(current_date).strftime('%Y-%m-%d')
PS: to explicitly distinguish between DM and MD, pass the argument dayfirst=True/False to parse, i.e. dayfirst=True represents DM and dayfirst=False represents MD.
This should do the job, w/o needing datetime:
"{2}-{0}-{1}".format(*(original_date.split("/")))

Comparing a python date variable with timestamp from select query

I want to take some action based on comparing two dates. Date 1 is stored in a python variable. Date 2 is retrieved from the database in the select statement. For example I want to retrieve some records from the database where the associated date in the record (in form of the timestamp) is later than the date defined by the python variable. Preferably, I would like the comparison to be in readable date format rather than in timestamps.
I am a beginner with python.
----edit -----
Sorry for being ambiguous. Here's what I am trying to do:
import MySQLdb as mdb
from datetime import datetime
from datetime import date
import time
conn = mdb.connect('localhost','root','root','my_db')
cur = conn.cursor()
right_now = date.today()// python date
this is the part which I want to figure out
The database has a table which has timestamp. I want to compare that timestamp with this date and then retrieve records based on that comparison. For example I want to retrieve all records for which timestamp is above this date
cur.execute("SELECT created from node WHERE timestamp > right_now")
results = cur.fetchall()
for row in results:
print row
first of all, I guess Date 1 (python variable) is a datetime object. http://docs.python.org/2/library/datetime.html
As far as I have used it, MySQLdb gives you results in a (python) datetime object if the sql type was datetime.
So actually you have nothing to do, you can use python datetime comparison methods with date 1 and date 2.
I am a little bit confused about "comparison to be in readable date format rather than in timestamps". I mean the timestamps is readable enough, right?
If Date 1 is timestamps data, then you just simply do comparison. If not, then convert it to timestamps or convert the date in database to date type, both way works.
If you are asking how to write the code to do the comparison, you would use either '_mysql' or sqlalchemy to help you. The detailed syntax can be found at any where.
Anyway, the question itself is not clear enough, so the answer is blur, too.

Categories

Resources