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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With