How to insert a value into SQLAlchemy TIMESTAMP column - python

I am trying to set value for timestamp column using SQLAlchemy, but I experience following error:
column "timestamp" is of type timestamp without time zone but expression is of type numeric
My table looks as folows:
class SomeTable(db.Model):
timestamp = Column(TIMESTAMP)
Insertion try looks like this:
SomeTable(timestamp=time.time())
When I use datetime.now() instead of time.time() the record is inserted into the table but when I select it from the database it has following format:
2019-04-02 11:44:24.801046
So it looks like TIMESTAMP field does not store timestamp format.
Is it regular postgres behaviour? Or am I missing something?

I think that is good, because next is correct:
Column('timestamp', TIMESTAMP(timezone=False), nullable=False, default=datetime.now())
so by default you have datetime.now() there, it is about presentation
datetime.now() will give you '2019-04-02 14:21:33.715782
datetime.now().isoformat() will give you '2019-04-02T14:31:09.071147'
Check it with: http://www.sqlfiddle.com/#!15/d0c6a/8
If you uncomment third insert you will get exact same exception as yours

Related

Query Django data base to find a column with a specific value and update that column value

I have tried very hard to understand how to update my data base, but struggling to even print out the value of the data returned.
My code in views.py:
#SET THE PLACEHOLDER DATE AND TIME AS A STRING AND CONVERT TO DATETIME
#QUERY THE DATA BASE TO FIND THE ROW WHERE END_END_TIME = PLACEHOLDER DATE AND TIME
#OUTPUT THE DATA TO THE TERMINAL
#UPDATE THE END_DATE_TIME TO CURRENT DATE AND TIME
date_time_placeholder = "2023-01-01 12:00:00"
datetime.strptime(date_time_placeholder, "%Y-%m-%d %H:%M:%S").date()
get_value = logTimes.objects.get(end_date_time = date_time_placeholder)
print(get_value)
The output:
logTimes object (155)
I can see in the admin site the code is working, it is finding the correct row, but I am not sure how to print the column data to the terminal instead of the just the object and ID.
What I am trying to achieve ultimately is to update the end_date_time in this row to the current date and time using datetime.now(), I am not having any success, not for the lack of trying for hours. Any help is appreciated.
You are getting the model object but not printing any of the model fields, which is why you are just seeing the object and ID. You can get the field by just printing get_value.end_date_time - if you then want to update it then you can do something like this, Django has a timezone module which I would recommend using:
from django.utils import timezone
get_value.end_date_time = timezone.now()
get_value.save()

Django models timestamp in MYSQL Db

I want to store time as unix timestamp in my MYSQL database, I have django project with model:
date = models.DateField()
But I didn't find any models.Timestamp()
or anything similiar. Is there a way to create timestamp column for MYSQL Db in Django? I found some articles here on stack but they are 5+ years old so there might a be a better solution now.
In Django, one usually uses a DateTimeField [Django-doc] for that. It is a column that thus stores a combination of date and time.
One can let Django automatically intialize (or update) the timestamp if the record is constructed or updated with auto_now_add=True [Django-doc] to initialize it when the record was created, and auto_now=True [Django-doc] to update. So it is a common pattern to see a (base)model like:
class TimestampModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
such that subclasses of the TimestampModel thus have two extra columns created and updated that store the time when the object was created and last updated respectively.
A datetime column has a larger range, as is specified in the MySQL documentation:
The DATETIME type is used for values that contain both date and time
parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD hh:mm:ss' format. The supported range is '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date
and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

Searching a date with parameter 'LIKE'

I am building a small program in Python and SQlite where a client can type a date in the format YYYY-MM-DD and get back all the plays that take place in that specific date. All the plays are store in Play.db which saves the date as: YYYY-MM-DD HH:MM
I do not want the user to type the exact date with hour and minutes. He just has to type the year-month-day and all the plays in that specific date should appear.
I realise that I need the keyword 'LIKE' and pass my variable between '%'variable'%' in order to get a similar (not exact) match.
However I am not sure how to do so by using the syntax of my SQLite query:
user_input = input("Please, type the date of the play in format: 'YYYY-MM-DD':")
search_date = """SELECT * FROM play WHERE play_date LIKE ? """
cursor.execute(search_date, [(user_input)])
results = cursor.fetchall()
The issue is that 'results' is not populated because the SQL query is looking for exact match.
THEREFORE I tried with %user_input% or %?% but, obsiously, the variable '%user_input%' or %?% is not defined.
I understand how logically is should be done:
how to search similar strings in SQLite
But I am not sure how the "LIKE '%'variable'%'" can be obtained using my code syntax.
import datetime
user_input = datetime.datetime(input("Please, type the date of the play in format: 'YYYY-MM-DD':"), '%Y-%m-%d')
# 2011-11-11
search_date = f'SELECT * FROM play WHERE play_date LIKE {user_input}'
print(search_date)
# SELECT * FROM play WHERE play_date LIKE 2011-11-11
Is this what you're looking for?
Edited to prevent sql injections
Use the date function in your query to just compare the dates of your stored datetime values and user input.
SELECT * FROM play WHERE date(play_date) = date(?)
You need a date function. Also you can use slicing for the string. Like:
theDate = input() #example: 2018-12-24
Year = theDate[:3]
Month = theDate[5:6]
Day = theDate[8:9]
Good day,
Well it may not be exactly what you want but I would share you some pieces of code I wrote when I wanted to build something like this but this time using Flask and SQLAlchemy.
First is to convert the data to a date/datetime to ensure the data is valid
converted_date = datetime.datetime.strptime(user_input, "%Y-%m-%d").date()
Converted to regular SQL query should be
SELECT * FROM play WHERE play_date LIKE {"%" + converted_date}
Please note that the "%" is very important, and putting it at the beginning means you want to search for any date that starts with the inputted date.

Group By using Timestamp in Django Queryset

I have one model where each entry is stored and its created time is stored. The time is not a datetime object a timestamp. Timestamp field of model is shown below :
logged_at = models.CharField(_('log time'), max_length=128,
default=time.time)
If above field is datetime field then I can write an query which can group by records using datetime field like :
MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(logged_at))', [])).values('in_time', 'name').annotate(count=Count('name'))
But I am not able to query the timesatmp field in same way , It gives me the error date/time field value out of range
I have also tried to use functions like to_timestamp nut still no success
MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(to_timestamp(logged_at)))', [])).values('in_time', 'name').annotate(count=Count('name'))
Error : function to_timestamp(character varying) does not exist
Database I am using is Postgres
As #Willem mentioned in comment that timestamp must not be stored in CharField. So We can try to change type of field at runtime like given below.
MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(to_timestamp(logged_at::float)))', [])).values('in_time', 'name').annotate(count=Count('name'))
IN above query I have changed type of logged_at to float and it works fine for me, you can also change it to int.

Retrieve created_at timestamp from pgsql

I'm a Python newbie. I wrote an sql query to retrieve created_at timestamp in pgsql. When I called the method strftime('%x') on it, I got this error:
AttributeError: 'long' object has no attribute 'strftime'
This is the query:
SELECT created_at FROM rating WHERE user_id = 'xxxxx' ORDER BY id DESC LIMIT 2;
When I printed the result of the query, I merely got [(3L,)] which is just one of the two created_at times expected. How do I convert this back to python's datetime?
strftime looks like it's not callable, have you imported DateTime?
Also, when calling strftime you'll need to format it, for example created_at.strftime('%y %B %d').
Finally, it's actually quicker to process and convert the time in SQL rather than using strftime.
A simpler and more performant solution would be to just format in the SQL itself:
SELECT to_char(created_at,'YY-MM-DD HH24:MI:SS') FROM rating WHERE user_id = 'xxxxx' ORDER BY id DESC LIMIT 2;

Categories

Resources