I came across an interesting situation.
我遇到了一个有趣的情况。
class Company(models.Model):
date = models.DateField()
time = models.TimeField()
When using this class:
当使用这个类:
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.
Django决定使用在格式中定义的datetime_input_format。py文件。这是有意义的,因为我将一个datetime.now()传递给两个字段。
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.
我认为我可以让Django分别使用DATE_INPUT_FORMATS和time_input_format,如果我只传入当前日期和当前时间。
Something like this:
是这样的:
c = Company(date=datetime.date.now(), time=datetime.time.now())
But this throws an exception as now doesn't exist like that. Is there a different way to achieve this?
但这引发了一个异常,因为现在不存在这样的异常。有不同的方法来实现这一点吗?
Many Thanks,
非常感谢,
3 个解决方案
#1
112
For the date, you can use datetime.date.today()
or datetime.datetime.now().date()
.
对于日期,可以使用datetime.date.today()或datetime.datetime.now().date()。
For the time, you can use datetime.datetime.now().time()
.
现在,您可以使用datetime.datetime.now().time()。
However, why have separate fields for these in the first place? Why not use a single DateTimeField
?
但是,为什么一开始就有单独的字段呢?为什么不使用一个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.
如果只需要一个或另一个函数,则可以在模型上定义helper函数,该函数返回.date()或.time()。
#2
45
import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015
For the time
的时间
from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18
#3
7
import datetime
datetime.date.today() # Returns 2018-01-15
datetime.datetime.now() # Returns 2018-01-15 09:00
#1
112
For the date, you can use datetime.date.today()
or datetime.datetime.now().date()
.
对于日期,可以使用datetime.date.today()或datetime.datetime.now().date()。
For the time, you can use datetime.datetime.now().time()
.
现在,您可以使用datetime.datetime.now().time()。
However, why have separate fields for these in the first place? Why not use a single DateTimeField
?
但是,为什么一开始就有单独的字段呢?为什么不使用一个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.
如果只需要一个或另一个函数,则可以在模型上定义helper函数,该函数返回.date()或.time()。
#2
45
import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015
For the time
的时间
from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18
#3
7
import datetime
datetime.date.today() # Returns 2018-01-15
datetime.datetime.now() # Returns 2018-01-15 09:00