Reputation: 101
I was wondering how can i send a time to django DateTimeField
by a django-admin command class , and by time i mean the actual hour and minute not the date. thanks
my django admin command class
class Command(BaseCommand):
def handle(self, *args, **kwargs):
title = 'new new post'
try:
MyModel.objects.create(
title=title,
mytime= '???',
)
print('%s added' % (title,))
except:
print('error')
my model
class MyModel(models.Model):
title = models.CharField(max_length=250)
mytime = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.title
Upvotes: 0
Views: 112
Reputation: 9359
Since you're using DateTimeField
, you can't save only time, but you can extract the time from it later (record.mytime.time()
).
You're looking for function datetime.now:
from datetime import datetime
MyModel.objects.create(
title=title,
mytime=datetime.now(),
)
However Django provides more convenient way how to do this - DateTimeField has a flag auto_now, which sets the time automatically during saving (or auto_now_add
if you want to set it only once when the model is created)
class MyModel(models.Model):
mytime = models.DateTimeField(null=True, blank=True, auto_now=True)
Upvotes: 1