简体   繁体   中英

Timezone - Make non-UTC datetime timezone aware

I have a case where I get an CET datetime (via my API) and I want to save it in my django database.

When I do this I always get a runtime warning:

datetime.fromtimestamp(last_content_update)

When I add the replace part I don't get the error but my date is not correct (1h shift):

datetime.fromtimestamp(last_content_update).replace(tzinfo=utc)

Any idea how I can load my datetime timezone aware?

Thanks!

Ok, finally I found out that the fromtimestamp() takes an timezone parameter!

Just do it like this:

datetime.fromtimestamp(last_content_update, tz=pytz.timezone("Europe/Paris"))

Here is a link to the documentation.

You need to do this in two steps:

  1. First, make the datetime timezone-aware - in your case, using the CET (Central European Time) timezone.
  2. Second, convert the datetime to UTC before saving it. This is because Django stores datetimes as UTC :

When support for time zones is enabled, Django stores datetime information in UTC in the database...

This can be done like this:

import pytz    
from django.utils import timezone

# Convert the naive datetime into a CET datetime
local_datetime = timezone.make_aware(naive_datetime, pytz.timezone('CET'))

# Convert the CET datetime to UTC
utc_datetime = local_datetime.astimezone(timezone.utc)

# Now it can be saved in the database on a model field
MyDateModel.objects.create(title='Another date model',
                           created=utc_datetime)

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