I have a date which I obtain from an API. It is in the form of 2015-01-01T15:04:23Z.
How can I accept this date into a model using Flask-SQLAlchemy?
So far I have tried,
date = db.Column(db.DateTime)
and
date = db.Column(db.DateTime(timezone=True))
which gives me the error
StatementError: (exceptions.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input.
Also, when I retrieve it using a get, I need it to be in the exact same format.
The dateutil python module parses it well but when I retrieve it from the table, I need to get 2015-01-01T15:04:23Z.
>>> from dateutil.parser import parse
>>> parse('2015-01-01T15:04:23Z')
datetime.datetime(2015, 1, 1, 15, 4, 23, tzinfo=tzutc())
You need to convert the string into a Python datetime object, which you can do using time.strptime:
record.date = time.strptime(mytime, "%Y-%m-%dT%H:%M:%SZ")
Then you can safely set it on your instance and commit it.
To get it back in the same format, use time.strftime on the other side:
time.strftime("%Y-%m-%dT%H:%M:%SZ", record.date)
And of course remember to watch out that the order of the arguments is different between strptime and strftime :)
If you need to change/update the format, see time.strftime here : https://docs.python.org/2/library/time.html
Related
I have built a web app in Python and Flask and am having trouble pulling the date and time from my SQLite database.
I enter the date into the DB with the following line-
order.order_placed = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Which with my current example enters the following into the DB -
2018-05-01 12:08:49
But when I call order.order_placed I get datetime.date(2018, 5, 1)
Even if I call str(order.order_placed) I get '2018-05-01'
Can someone help me get the full date and time out of the database? Thanks!
It's possible that you're using DateField when in actuality you want to use DateTimeField.
Furthermore, you don't need to call strftime before storing the data. Peewee works nicely with Python datetime objects.
I have the following model class
class Transaction(models.Model):
quantity = models.IntegerField(default=0)
sell_time = models.DateTimeField()
When I fetch "sell_time" from the model, I am getting datetime in the following format
2014-10-01 08:09:46.251563+00:00
my question is, if it is not in the format like
year-month-day hour:minutes:seconds
how can I convert to python datetime object like
datetime.datetime(2014, 10, 1, 08, 09, 46, 540535)
many thanks
Did you print it? If you print a datetime object, it is serialized to a string but it is a datetime. You can use it as any other datetime.
You are seeing that because you did not set the correct time zone. Use the UTC time and then you can format .strftime("format") the time accordingly to each locale, you can install pytz and enable it in the settings to handle all the hustle. Always use UTC datetime object because then you can get what ever time you want knowing the zone your user is in. Documentation from Django
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()
I've been trying to find a way to create an ISODate object whith pyMongo client, but without any success so far.
I use http://pypi.python.org/pypi/pymongo3 client, which is the only serious one available in Python 3 for now, but the problem doesn't seem to come from this specific pymongo version.
I'd like to know if any of you has found a solution to use this MongoDB object type from a pymongo client... thanks for your help !
You just need to store an instance of datetime.datetime.
Inserting from the python shell:
>>> c.test.test.insert({'date': datetime.datetime.utcnow()})
ObjectId('4e8b388367d5bd2de0000000')
>>> c.test.test.find_one()
{u'date': datetime.datetime(2011, 10, 4, 16, 46, 59, 786000), u'_id': ObjectId('4e8b388367d5bd2de0000000')}
Querying in the mongo shell:
> db.test.findOne()
{
"_id" : ObjectId("4e8b388367d5bd2de0000000"),
"date" : ISODate("2011-10-04T16:46:59.786Z")
}
For those who are wondering how to create ISODate from timestamp:
ts = time.time()
isodate = datetime.datetime.fromtimestamp(ts, None)
This will create datetime object with no timezone. When inserted to MongoDB it will get converted to proper ISODate().
Also, I strongly recommend looking at Python TimeTransitionsImage. Note that tuple here is named tuple (equivalent to struct in C). And also note that tuple fields are not the same as in C counterparts, even though the naming is the same (for instance, tm_wday starts with Monday and not Sunday).
Actually that does not work either. When you try to use either utcfromtimestamp or fromtimestamp, the program errors out saying that it needs a float. Just parse the string into a date time object and use that directly in the Mongodb. filter
from_dt = datetime.strptime('2018-04-01','%Y-%m-%d')
#from_dts = datetime.utcfromtimestamp(from_dt)
to_dt = datetime.strptime('2018-04-30','%Y-%m-%d')
#to_dts = datetime.utcfromtimestamp(to_dt)
filterCondition = {
"LastLogin" : { "$lte" : to_dt},
"LastLogin" : { "$gte" : from_dt}
}
And then
db[(colName)].find({ "<colName>" : filterCondition })
Would work...
result = db.objects.insert_one(
{"last_modified": datetime.datetime.utcnow()})
Here utc stands for Universal Time Coordinates.
For create a document with specific date, for example 03/10/1999, run this:
from datetime import datetime
from pymongo import MongoClient
db = MongoClient().db_name
date = datetime(1999, 03, 10)
db.collection.insert_one({'date': date})
I am trying to read a date of format DD-MM-YYYY format from HTML and Compare it with the datetime field named as widget_created_at in my model.
if data["field"] == "widget_created_at":
date = datetime.strptime(data["data"], "%d-%m-%Y").date()
if data["option"] == "before":
filter_query = Q(widget_created_at__lt=date)
Then whenever this query is used for filtering in the below code
blogs = blogs.filter(filter_query)
RunTime warning for naive datetime appears. I tried every solution i found from here and google but the Error is still there. Please tell me how to avoid it.
Thanks
The date you are creating for your filter has no timezone.
Have you looked at pytz to "localize" the filter date? This would allow you to add a timezone to the filter date?