Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current date and current time only respectively in Django?

I came across an interesting situation when using this class:

class Company(models.Model):     date = models.DateField()     time = models.TimeField() 
c = Company(date=datetime.datetime.now(), time=datetime.datetime.now())  

Django decides to use DATETIME_INPUT_FORMATS defined within the formats.py file. Which makes sense, because I am passing in a datetime.now() to both fields.

I think I could make Django to use DATE_INPUT_FORMATS and TIME_INPUT_FORMATS respectively, if I passed in only the current date and current time in.

Something like this:

c = Company(date=datetime.date.now(), time=datetime.time.now())  

But this obviously throws an exception as now doesn't exist like that. Is there a different way to achieve this?

like image 776
Houman Avatar asked Aug 19 '12 21:08

Houman


People also ask

How can I get current date and time in Django?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.

How do I get the current date in python?

today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.

Is there a time field in Django?

TimeField is a time field which stores time, represented in Python by a datetime. time instance. As the name suggests, this field is used to store an object of datetime created in python.


1 Answers

For the date, you can use datetime.date.today() or datetime.datetime.now().date().

For the time, you can use datetime.datetime.now().time().


However, why have separate fields for these in the first place? Why not use a single DateTimeField?

You can always define helper functions on the model that return the .date() or .time() later if you only want one or the other.

like image 193
Amber Avatar answered Sep 25 '22 15:09

Amber