MattG
MattG

Reputation: 1932

How to format Django's timezone.now()

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 ?

Upvotes: 18

Views: 21591

Answers (3)

bdoubleu
bdoubleu

Reputation: 6107

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')

To get the local time, defined by the current time zone setting TIME_ZONE, you can use localtime.

from django.utils import timezone, dateformat

formatted_date = dateformat.format(
    timezone.localtime(timezone.now()),
    'Y-m-d H:i:s',
)

Upvotes: 33

dmitri
dmitri

Reputation: 3294

It is not clear what you are asking. Your examples show different format and different time values too. Although the time value difference doesn't look like a difference between local and UTC time I'll assume that part of the problem was conversion between time zones.

from django.utils import timezone
d = timezone.now()
print(d)
print(d.strftime("%Y-%m-%d %H:%M:%S"))
print(timezone.localtime(d).strftime("%Y-%m-%d %H:%M:%S"))

The output is

2021-01-13 07:25:17.808062+00:00
2021-01-13 07:25:17
2021-01-13 18:25:17

Upvotes: 9

Prateek
Prateek

Reputation: 1556

You can use the code below:

from datetime import datetime

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

Link - Ref

Upvotes: 5

Related Questions