Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Django's timezone.now()

Tags:

python

django

I am trying to autofill a django datetimefield using a timezone aware date. Using Django's timezone.now() outputs Aug. 21, 2019, 5:57 a.m.. How can I convert this to 2019-08-21 14:30:59 ?

like image 723
MattG Avatar asked Aug 21 '19 11:08

MattG


People also ask

What does timezone NOW () return?

timezone. now() useful. This function returns the current date and time as a naive datetime when USE_TZ = False and as an aware datetime when USE_TZ = True .

What is the format of datetime in Django?

And, because the format is dd/mm/yyyy, we must use a slash to separate the date, month and year.


2 Answers

If you want to do the transformation on the backend you can use Django's built in utility dateformat.

from django.utils import timezone, dateformat

formatted_date = dateformat.format(timezone.now(), 'Y-m-d H:i:s')
like image 164
bdoubleu Avatar answered Sep 24 '22 07:09

bdoubleu


You can use the code below:

from datetime import datetime

date_string = datetime.strftime(timezone.now(), '%Y-%m-%d %H:%M:%s')

Link - Ref

like image 39
Prateek Avatar answered Sep 22 '22 07:09

Prateek