Sudharsan Venkatraj
Sudharsan Venkatraj

Reputation: 581

How to set TimeField alone 00:00:00: in django

Here i have mentioned My model.py in this date field default i want to assign timezone as 00:00:00, so please help me to do this.

Models.py

class Dummy(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateTimeField(null=True,auto_now_add=True)

Expected output like

{
    "id": 1,
    "name": "xxxx",
    "date": "2018-09-26T00:00:00Z"
}

Actual Output

{
    "id": 1,
    "name": "xxxx",
    "date": "2018-09-26T05:52:26.626604Z"
}

Upvotes: 0

Views: 1981

Answers (4)

Selcuk
Selcuk

Reputation: 59164

You can remove the time part of a datetime object using the .replace() method:

self.date = self.date.replace(hour=0, minute=0, second=0, microsecond=0)

This will result in:

datetime.datetime(2018, 9, 26, 0, 0)

Upvotes: 0

Akash Kinwad
Akash Kinwad

Reputation: 815

From the Django documents for Field.default:

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

So do this:

from datetime import datetime, timedelta

def default_start_time():
    now = datetime.now()
    start_time = now.replace(hour=00, minute=0, second=0, microsecond=0)
    return start_time 

class Dummy(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateTimeField(null=True,auto_now_add=True,default=default_start_time)

Upvotes: 1

kungphu
kungphu

Reputation: 4849

It seems like you don't want the time component at all; it doesn't make sense to store it if you intend to zero it out in all cases.

Keep just the date, and in your serializer, use the date to instantiate a datetime.

from datetime import date, datetime


# Where t would normally be a date from your model...
t = date.today()
print(datetime(t.year, t.month, t.day).isoformat())
# 2018-09-26T00:00:00

You haven't given us information regarding how you're generating this JSON, but if you're using Django's built-in serialization, you can write a custom encoder to handle translating dates into zero-time datetimes in this manner.

Upvotes: 0

user10356004
user10356004

Reputation:

Use DateField instead of DateTimeField.

Upvotes: 0

Related Questions