Django models timestamp in MYSQL Db - python

I want to store time as unix timestamp in my MYSQL database, I have django project with model:
date = models.DateField()
But I didn't find any models.Timestamp()
or anything similiar. Is there a way to create timestamp column for MYSQL Db in Django? I found some articles here on stack but they are 5+ years old so there might a be a better solution now.

In Django, one usually uses a DateTimeField [Django-doc] for that. It is a column that thus stores a combination of date and time.
One can let Django automatically intialize (or update) the timestamp if the record is constructed or updated with auto_now_add=True [Django-doc] to initialize it when the record was created, and auto_now=True [Django-doc] to update. So it is a common pattern to see a (base)model like:
class TimestampModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
such that subclasses of the TimestampModel thus have two extra columns created and updated that store the time when the object was created and last updated respectively.
A datetime column has a larger range, as is specified in the MySQL documentation:
The DATETIME type is used for values that contain both date and time
parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD hh:mm:ss' format. The supported range is '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date
and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

Related

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.

Manually set models.DateTimeField

I've created a Transaction table which I want to test, one of the most important field of this table is:
models.DateTimeField(
default=timezone.now)
In order to test my app with the database, I need historical data. Currently when I create a transaction, it sets the date and time automatically, so it is always current.
I need previous month data and I'm wondering if I can manually set the above field when I create a transaction?
Currently when I create a transaction, it sets the date and time automatically
You can always override that default value before you save the model instance, for the example below let's assume your DateTimeField with the default value is called timestamp:
import datetime
transaction = Transaction()
transaction.timestamp = timestamp # Overrides the default
# You can use a datetime.datetime
# instance as value
# transaction.timestamp = datetime.datetime(year, month, day, hour, minute, second)
transaction.save()
"Override" is a big word, since the default is only used when you don't provide a value.
and what is the format of the timestamp? is it timestamp = datetime (year, month, day, hour..)?
Yes the DateTimeField field will accept a datetime.datetime object.

Django: Order by Time in DateTime Field

I have a datetime field.
date = models.DateTimeField()
Im trying to do a query set for all the entries on that date and then order it by time. I get all the entries like this...
todays_entries = model.objects.filter(date__range=(start_date, end_date))
I understand if I wanted to order it by date i would add a order_by('date') method but the time is still all off in terms of the order...how can I go about ordering the time?

Using DateTimeField in Django with Oracle

I have table in Oracle, which has field of DATE type. Also I have model in Django with DateTimeField. I want to save datetime in Oracle's DATE field, but Django ORM raises such exception:
DatabaseError: ORA-01830: date format picture ends before converting entire input string
I tried to use Django DateField, but it didn't save datetime, only date. How can I save datetime in Oracle using Django (I don't want to use DATETIME field in Oracle because of legacy problems).
My model:
class MyModel(models.Model):
filled_date = models.DateTimeField(db_column='filled_date')
I found the solution for problem.
Oracle waits format 'YYYY-MM-DD HH24:MI:SS', but datetime.datetime.now() returns string like this: u'2013-10-18 05:50:44.332577'.
The solution:
model.filled_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
model.save()

django's DateField model field and acceptable values

I'm having a bit of trouble with django's DateField model field. Shouldn't it be able to accept fiveDaysLater as a valid date object? When I try to add fiveDaysLater into the database, I get an error saying cannot add null value to date. However, the second I change the date field to a regular CharField, the fiveDaysLater value is added to the database with no problem. fyi if I print fiveDaysLater, I get 2011-09-28
My view:
def myView():
now = datetime.date.today()
fiveDaysLater = now + datetime.timedelta(days=5)
newDate = Speech(date = fiveDaysLater)
newDate.save()
My model
class Speech(models.Model):
date = models.DateField()
"However, the second I change the date field to a regular CharField..." Just a suspicion but if you made this change in your code, make sure to delete and recreated the Speech table using syncdb, otherwise, sqlite will not be aware of this change. (or you could change the datatype using sqlite exporer for firefox or something like that...)

Categories

Resources