简体   繁体   中英

Python: Get aware datetime string from aware datetime

I have an aware datetime-object and want to return an aware datetime-string. However when I do

obj.strftime("%e %b %Y %H:%M:%S")

it returns a UTC-based string (even though TIME_ZONE -setting is set right).

How can I get a localised datetime-string?

EDIT: I want the timezone of django to get applied

You can use the module dateformat inside your project, it allows to get the timezone from your settings :

from django.utils import dateformat

timezoned_date = dateformat.DateFormat(obj).format('jS F Y H:i:s')

EDIT :

This works fine with unaware datetime objects, better use django.utils.timezone.localtime with aware dates.

I had to use localtime(obj) :

localtime(obj).strftime("%e %b %Y %H:%M:%S")

worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM