简体   繁体   中英

Convert datetime obj to timezone-aware datetime

I have the following date I am trying to save:

timestamp = datetime.datetime.strptime(timestamp_raw, '%Y-%m-%dT%H:%M:%SZ')

When I save it, I get the following Warning:

/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py:808:
RuntimeWarning: DateTimeField received a naive datetime
(2014-12-11 21:42:58) while time zone support is active. RuntimeWarning)

How would I convert my datetime object to a tz-aware datetime object?

Django provides a utility function for this:

from django.utils.timezone import make_aware

timestamp = make_aware(timestamp)

By default this will use the current time zone , which by default is TIME_ZONE . If that's not what you want you can pass the desired timezone as an argument to make_aware .

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