Reputation: 1932
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
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
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