[python] 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?

This question is related to python django django-models

The answer is


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

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

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.


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

import datetime

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

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to django-models

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries "Post Image data using POSTMAN" What does on_delete do on Django models? Django values_list vs values What's the difference between select_related and prefetch_related in Django ORM? Django Model() vs Model.objects.create() 'NOT NULL constraint failed' after adding to models.py django - get() returned more than one topic How to convert Django Model object to dict with its fields and values? How do I make an auto increment integer field in Django?