Retrieve created_at timestamp from pgsql - python

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;

Related

How to insert a value into SQLAlchemy TIMESTAMP column

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

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.

Error when retrieving Date from datetime.date object in Python

I want to retrieve date in the format of "May 01 2009" from datetime.date object. I have a table stored in MySQL database. It has Date column, and Time Column separately. Date in table is of the format,
2009-05-01
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[0]
Output is,
datetime.date(2009, 5, 1)
When I try the below command to extract the date in the way I want,
datetime.date.strftime("%b %d %Y", row[0])
I get an error as,
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
I just don't get it, when datetime.date object is provided, it raises an error.
Can anyone please help me. Thanks in advance.
strftime is a instance method of date objects, not a separate function:
print(row[0].strftime("%b %d %Y"))
The error message is trying to tell you that you're calling the uninstanced method (descriptor) from the date class directly, without passing an instance as first parameter.
For more info check date objects documentation.
It's a datetime.date object. It has a str() method which will solve your problem.
import datetime
date=datetime.date(2009,5,1)
datetime.date(2009, 5, 1)
str(d)
will result as
'2009-05-01'

How do I query for objects created before a certain hour in a day in Django?

In Django, I am trying to filter my query only to objects that were created before a certain hour in the day. I have a datetime field called 'created_at' that stored the datetime from which that object was created.
What I would like to do is:
query = query.filter(created_at__hour__lte=10)
Which I would expect to get all the objects that were created before 10am. However, when I try that I get a:
FieldError: Join on field 'created_at' not permitted. Did you misspell 'hour' for the lookup type?
I could loop through each day and get that day's objects, but that seems highly inefficient. Is there a way I can do this in a single query? If not, what is the fastest way to run this sort of filter?
__hour on a DateTimeField is a lookup type, so you can't mix it with another lookup type like __lte. You could construct a filter with Q objects, EG:
before_ten = Q(created_at__hour=0)
for hour in range(1, 11):
before_ten = before_ten | Q(created_at__hour=hour)
query = query.filter(before_ten)
If you can change your data model, it might be more convenient to save a creation time TimeField as well as your existing created_at.
In Django 1.9+, you can chain hour lookups like created_at__hour__lte, so the query from the question will work.
query = query.filter(created_at__hour__lte=10)
import datetime
start_time = datetime.datetime.now().replace(hour=00, minute=00)
certain_hour = 10
end_time = start_time.replace(hour=certain_hour)
query = query.filter(created_at__range=(start_time, end_time)

converting NDB Datetimeproperty to date

I have a NDB datetime property stored on Google App Engine. I'm trying to query for all records since yesterday by converting the datetime to a date, then filtering the query for anything greater or equal to yesterdays date. However, I am getting the following error:
follower_trans = fol.query(
datetime.datetime.date(fol.followed_date) >= self.yesterday).fetch()
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'DateTimeProperty'
If i use just datetime.date() it sends an error requiring an integer as an argument.
You can't do a conversion as part of the query, so you'll have to create 'yesterday' as a datetime and filter using that.
fol.followed_date is the model's property, not an entity's value. You cannot convert a property to a date, as it has no value. You need to fix the query constructor:
follower_trans = fol.query(fol.followed_date >= self.yesterday).fetch()
(assuming you've created self.yesterday as a datetime object.)
Also, it is proper to use a capital letter for any Class names. Should have been:
class Fol(ndb.Model):
followed_date = ndb.DateTimeProperty(auto_now_add = True)
and
Fol.query(Fol.followed_date >= self.yesterday).fetch()

Categories

Resources