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.
Related
I have tried very hard to understand how to update my data base, but struggling to even print out the value of the data returned.
My code in views.py:
#SET THE PLACEHOLDER DATE AND TIME AS A STRING AND CONVERT TO DATETIME
#QUERY THE DATA BASE TO FIND THE ROW WHERE END_END_TIME = PLACEHOLDER DATE AND TIME
#OUTPUT THE DATA TO THE TERMINAL
#UPDATE THE END_DATE_TIME TO CURRENT DATE AND TIME
date_time_placeholder = "2023-01-01 12:00:00"
datetime.strptime(date_time_placeholder, "%Y-%m-%d %H:%M:%S").date()
get_value = logTimes.objects.get(end_date_time = date_time_placeholder)
print(get_value)
The output:
logTimes object (155)
I can see in the admin site the code is working, it is finding the correct row, but I am not sure how to print the column data to the terminal instead of the just the object and ID.
What I am trying to achieve ultimately is to update the end_date_time in this row to the current date and time using datetime.now(), I am not having any success, not for the lack of trying for hours. Any help is appreciated.
You are getting the model object but not printing any of the model fields, which is why you are just seeing the object and ID. You can get the field by just printing get_value.end_date_time - if you then want to update it then you can do something like this, Django has a timezone module which I would recommend using:
from django.utils import timezone
get_value.end_date_time = timezone.now()
get_value.save()
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.
I need to delete a table record whenever tables record's timestamp or datetime matches current datetime in db. Problem is I cant get datetime values on console without using datetimes method if i use it I can't filter it .
here is my code
def query(request):
xx = datetime.datetime.now()
if dulesdb.objects.all():
zzz = dulesdb.objects.datetimes('request_time','second')
yyy = dulesdb.objects.filter(zzz > datetime.datetime.now())
print yyy.delete() # some trick this way
return HttpResponse('deleted')
If I understand your code correctly, you want to delete records having request_time greater than the current datetime.
To achieve this, you can filter your queryset to only get the corresponding records:
def query(request):
dulesdb.objects.filter(request_time__gt=datetime.datetime.now()).delete()
return HttpResponse('deleted')
This queryset will return you all records having their request_time attribute greater than the current time. You can then directly delete those records (with the delete() method).
You can replace the __gt suffix according to your needs (__gte: greater than or equal to, __lt: less than, etc.)
You'll find more info about field lookups in the official doc
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?
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...)