Error when retrieving Date from datetime.date object in Python - 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'

Related

What python object-type is compatible with the ms-access date/time field?

I have a piece of code that tries to insert a datetime.datetime into an ms-access datebase's date/time (not extended date/time) field, yet I keep getting the data type mismatch error message.
So my question is, which type do I use for this?
I tried using this code
print(type(timeCET))
>>>
datetime.datetime
and
crsr.execute("insert into WeatherAnalisis(Time_UTC) values ('timeCET.timedate')")
cnxn.commit()
>>>>
pyodbc.DataError: ('22018', '[22018] [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression. (-3030) (SQLExecDirectW)')
But it doesn't seem to work
You directly included the name of your datetime object as a quoted literal in SQL statement. As a result, Access throws an error since your are trying to insert a literal string value 'timeCET.timedate' (the name and not value of your actual datetime variable) into datetime column.
Instead, consider SQL parameterization. (Do not concatenate as single quotes will not work to enclose dates in Access SQL).
# PREPARED STATEMENT WITH QMARK
sql = "insert into WeatherAnalisis (Time_UTC) values (?)"
# EXECUTE QUERY WITH BINDED PARAM
crsr.execute(sql, timeCET)
cnxn.commit()
Whilst the original question does not specify where the variable timeCET originates from, once can see that it is a datetime from its type.
The problem seems to be one of matching types.
Given this, here is how to convert to a string:
import datetime as dt
# create a datetime
t = dt.datetime.utcnow()
print(t)
print(type(t))
# now convert to string
u = t.strftime("%m/%d/%Y, %H:%M:%S")
print(u)
print(type(u))
This is the output:
2022-03-26 17:00:52.998699
<class 'datetime.datetime'>
03/26/2022, 17:00:52
<class 'str'>
The original type (for variable t) was datetime.
This is now changed (for variable u) to string.
This can now be parsed into the database (or changed to a format that works).

Python date string to postgres usable date

Issue:
I stored some dates as text in my Postgres table, and I want to convert it over to actual dates, again in Postgres.
Im not sure if there is a better way to do this or what im doing wrong. I have pulled a bunch of data into a PostgreSQL database in just text format. As a result I need to go back through and clean it up. I am running into issues with the data. I need to convert it into a format that PostgreSQL can use. I went about pulling it back into python and trying to convert and kick it back. Is this the best way to do this? Also I am having issue with datetime.strptime.. I believe i've got the directive correct but no go. :/
import psycopg2
from datetime import datetime
# connect to the PostgreSQL database
conn = psycopg2.connect(
"dbname='postgres' user='postgres' host=10.0.75.1 password='mysecretpassword'")
# create a new cursor
cur = conn.cursor()
cur.execute("""SELECT "Hash","Date" FROM nas """)
# commit the changes to the database
myDate = cur.fetchall()
for rows in myDate:
target = rows[1]
datetime.strptime(target, '%B %d, %Y, %H:%M:%S %p %Z')
Here is a Postgres query which can convert your strings into actual timestamps:
select
ts_col,
to_timestamp(ts_col, 'Month DD, YYYY HH:MI:SS PM')::timestamp with time zone
from your_table;
For a full solution, you might take the following steps:
create a new timestamp column ts_col_new in your table
update that column using the logic from the above query
then delete the old column containing text
The update might look something like this:
update your_table
set ts_col_new = to_timestamp(ts_col, 'Month DD, YYYY HH:MI:SS PM')::timestamp with time zone;

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;

inserting timestamps with python cassandra prepared statements

Is it possible to insert a timestamp value into a Cassandra keyspace using prepared statements of Python Cassandra driver? When I tried to do that, I got the following error message:
Expected: <class 'cassandra.cqltypes.DateType'>, Got: <type 'str'>
I see that this problem had been discussed before. But not sure whether it has been resolved. How to do this? Doing the same using simple statements would be inefficient.
Yes, you can insert a timestamp value via prepared statements by binding a datetime object. I have tried it with success.
Like Aaron said, you need to use a datetime object. Given a simple table definition:
CREATE TABLE stackoverflow2.timestamps (
bucket text,
value timestamp,
PRIMARY KEY (bucket, value)
) WITH CLUSTERING ORDER BY (value DESC)
This code will INSERT ten timestamps into the timestamps table, given a valid (connected) session:
preparedInsert = session.prepare(
"""
INSERT INTO stackoverflow2.timestamps (bucket,value) VALUES (?,?);
"""
)
#end prepare statements
for counter in range(1,10):
currentTime = datetime.datetime.today()
bucket = currentTime.strftime("%Y%m")
session.execute(preparedInsert,[bucket,currentTime])
Essentially, the datetime.datetime.today() line creates a datetime object with the current time. The strftime creates a string time bucket from it, and then the preparedInsert puts them both into Cassandra.

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