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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With