[Fixed]-How to format Django's timezone.now()

26👍

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

9👍

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
👤dmitri

5👍

You can use the code below:

from datetime import datetime

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

Link – Ref

Leave a comment