如何在 Django 中分别获取当前日期和当前时间?

在使用这个类时,我遇到了一个有趣的情况:

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

Django 决定使用在 Py文件中定义的 DATETIME_INPUT_FORMATS。 这是有道理的,因为我将 datetime.now()传递给这两个字段。

我认为我可以使 Django 分别使用 DATE_INPUT_FORMATSTIME_INPUT_FORMATS,如果我只传入当前日期和当前时间。

就像这样:

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

但这显然抛出了一个异常,因为现在不存在这样的异常。有没有不同的方法来达到这个目的?

184909 次浏览

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.

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
import datetime


datetime.date.today()  # Returns 2018-01-15


datetime.datetime.now() # Returns 2018-01-15 09:00
 import datetime

Current Date and time

     print(datetime.datetime.now())
#2019-09-08 09:12:12.473393

Current date only

     print(datetime.date.today())
#2019-09-08

Current year only

     print(datetime.date.today().year)
#2019

Current month only

     print(datetime.date.today().month)
#9

Current day only

     print(datetime.date.today().day)
#8

Another way to get datetime UTC with milliseconds.

from datetime import datetime


datetime.utcnow().isoformat(sep='T', timespec='milliseconds') + 'Z'


2020-10-29T14:46:37.655Z

A related info, to the question...

In django, use timezone.now() for the datetime field, as django supports timezone, it just returns datetime based on the USE TZ settings, or simply timezone 'aware' datetime objects

For a reference, I've got TIME_ZONE = 'Asia/Kolkata' and USE_TZ = True,

from django.utils import timezone
import datetime


print(timezone.now())  # The UTC time
print(timezone.localtime())  # timezone specified time,
print(datetime.datetime.now())  # default local time


# output
2020-12-11 09:13:32.430605+00:00
2020-12-11 14:43:32.430605+05:30  # IST is UTC+5:30
2020-12-11 14:43:32.510659

refer timezone settings and Internationalization and localization in django docs for more details.