I have a SQLite DB which has few columns of type datetime.
These column store time (just the time and not the date) in HH:mm:ss format.
When I try to access this field it is returned as null.
In models.py this field have been mapped to equivalent models.DateTimeField.
What is the correct way of accessing such fields?
Is it required that models.DateTimeField HAS TO BE stored in YYYY-MM-DD HH:mm:ss format insqlite?
I am not suprised that DateTimeField expects both a date and a time.
Try TimeField instead.
(Please note that SQLite does not have a native date/time type; it's just a string.)
Related
I have a model which contains a datetime field.
I need to write the rows from that model table to excel sheet.
As the model field is datetime field, when writing to the excel, it's writing a number like 45976 etc for dates instead of 2020-04-01 as string.
I'm getting values of rows using queryset.values_list(*fields_to_fetch) This fields_to_fetch contains the datetimefield I'm looking for. When I print the type, it is saying DateTimeField in the console.
Is there any way to get the datetimefield as string type?
I was able to convert each item in the values_list() to list and then the datetimefield into string and append it to a new list and write to excel.
I'm looking for a way to avoid all this.
Use Cast(...) database function,
from django.db.models.functions import Cast
from django.db.models import CharField
cast_expr = Cast('date_time_field', output_field=CharField())
data = ModelKlass.objects.annotate(dt_as_str=cast_expr).values_list('dt_as_str')
I'm creating a SQLite database on python and am on the stage of creating tables. Within the table below I'm storing a date to an ID and need help with the datatype on the date. I'm not sure if there's an inbuilt one or if I do text and then format the date when inputting the data. I also have a similar question in another table but this type for storing the year. Thanks in advance.
SQLite does not have an inbuilt date column type.
2.2. Date and Time Datatype SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And
Time Functions of SQLite are capable of storing dates and times as
TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian
day numbers, the number of days since noon in Greenwich on November
24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER
as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
Column types in SQLite are very flexible and the type is largely irrelevant as you can store any type of data (INTEGER, REAL, TEXT, BLOB NULL) in any type of column (the one exception being the rowid column or an alias thereof (INTEGER PRIMARY KEY (with or without AUTOINCREMENT)) in which case the value must be an integer (64 bit signed)).
However, SQLite does have date and time functions that act on the data being stored in specific recognosed formats.
All the recognised date formats are directly sortable.
You may wish to have a look at :-
Datatypes In SQLite Version 3
SQL As Understood By SQLite - Date And Time Functions
Question regarding the use of TimestampField in PeeWee using Python 3.6. My model contains the following attribute:
timestamp= peewee.TimestampField(utc=True)
I store a timestamp as follows:
obj = TestObject(timestamp = Decimal(UnixtimestampString))
obj.save()
print(type(TestObject.get().timestamp))
Output:
Type: <class 'datetime.datetime'>
Is this normal behavior? I would like to retrieve the timestamp as Decimal (the way I put it in). Obviously I can convert it, but I was wondering why one would use TimestampField instead of DateTimeField when both return a DateTime object.
Is the only difference, the way the data is entered? (As a DateTime object in case of DateTimeField vs unix timestamp in Integer/Decimal for the TimestampField.)
The TimestampField exists to store datetimes, expressed as timestamps, as an integer...but the Python representation is a datetime object.
If you want to work with integer (or float) timestamps, then there's no reason to use TimestampField, just use an IntegerField or FloatField.
According to this, it's not possible to save datetime.date instances in MongoDB using Python and pymongo. It says in the FAQ that it's an unsupported type and to use datetime.datetime instead.
However, it's listed (as #9) in the BSON data types page here, so is this just out-of-date, or is there a reason I can't use python this data type?
From mongo docs: http://docs.mongodb.org/manual/reference/bson-types/#document-bson-type-date
The official BSON specification refers to the BSON Date type as the UTC datetime.
So, there is while it is written as "Date", it's still a datetime in BSON. If you want just date, you can set the hours/minutes/seconds/ms to 0.
Also, as specified on the docs about timestamp:
*NOTE
The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.*
The difference between datetime and timestamp is: datetime is an abstraction of date (day, month, year) and time (hour, min, second), and timestamp is the number of seconds since epoch.
I need to insert rows into PG one of the fields is date and time with time stamp, this is the time of incident, so I can not use --> current_timestamp function of Postgres at the time of insertion, so how can I then insert the time and date which I collected before into pg row in the same format as it would have been created by current_timestamp at that point in time.
If you use psycopg2 (and possibly some other client library), you can simply pass a Python datetime object as a parameter to a SQL-query:
from datetime import datetime, timezone
dt = datetime.now(timezone.utc)
cur.execute('INSERT INTO mytable (mycol) VALUES (%s)', (dt,))
(This assumes that the timestamp with time zone type is used on the database side.)
More Python types that can be adapted into SQL (and returned as Python objects when a query is executed) are listed here.
A timestamp does not have "a format".
The recommended way to deal with timestamps is to use a PreparedStatement where you just pass a placeholder in the SQL and pass a "real" object through the API of your programming language. As I don't know Python, I don't know if it supports PreparedStatements and how the syntax for that would be.
If you want to put a timestamp literal into your generated SQL, you will need to follow some formatting rules when specifying the value (a literal does have a format).
Ivan's method will work, although I'm not 100% sure if it depends on the configuration of the PostgreSQL server.
A configuration (and language) independent solution to specify a timestamp literal is the ANSI SQL standard:
INSERT INTO some_table
(ts_column)
VALUES
(TIMESTAMP '2011-05-16 15:36:38');
Yes, that's the keyword TIMESTAMP followed by a timestamp formatted in ISO style (the TIMESTAMP keyword defines that format)
The other solution would be to use the to_timestamp() function where you can specify the format of the input literal.
INSERT INTO some_table
(ts_column)
VALUES
(to_timestamp('16-05-2011 15:36:38', 'dd-mm-yyyy hh24:mi:ss'));
Just use 'now'
http://www.postgresql.org/docs/8.0/static/datatype-datetime.html
Date and time input is accepted in almost any reasonable format,
including ISO 8601, SQL-compatible, traditional POSTGRES, and others.
For some formats, ordering of month, day, and year in date input is
ambiguous and there is support for specifying the expected ordering of
these fields.
In other words: just write anything and it will work.
Or check this table with all the unambiguous formats.
Sure, just pass a string value for that timestamp column in the format: '2011-05-16 15:36:38' (you can also append a timezone there, like 'PST'). PostgreSQL will automatically convert the string to a timestamp. See http://www.postgresql.org/docs/9.0/static/datatype-datetime.html#DATATYPE-DATETIME-INPUT
from datetime import datetime as dt
then use this in your code:
cur.execute('INSERT INTO my_table (dt_col) VALUES (%s)', (dt.now(),))
Just use
now()
or
CURRENT_TIMESTAMP
I prefer the latter as I like not having additional parenthesis but thats just personal preference.