简体   繁体   中英

how to convert datetime from certain timezone to UTC ? django DateTimeField

I am having trouble dealing with dealing with DateTimeField field.

The question is, lets say i created datetime with timezone like that

>>> x = datetime.tzinfo("Asia/Kuala_Lumpur")
>>> y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x)

i want to convert "y" to UTC so that I can save it to DateTimeField

How do I do that ?

Here is rest of my console test

>>> a = Attendance.objects.last()
>>> a
<Attendance: wawa>
>>> a.updated_at
datetime.datetime(2018, 7, 29, 13, 37, 26, 459259, tzinfo=<UTC>)
>>> a.updated_at = timezone.now()
>>> a.updated_at
datetime.datetime(2018, 8, 11, 8, 49, 5, 381198, tzinfo=<UTC>)
>>> a.updated_at = timezone.now()
>>> a.updated_at
datetime.datetime(2018, 8, 11, 8, 52, 33, 243825, tzinfo=<UTC>)
>>> x = datetime.tzinfo("Asia/Kuala_Lumpur")
>>> y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x)
>>> y
datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=<datetime.tzinfo object at 0x113ac6600>)
>>> y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x)
>>> y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x)
>>> a.updated_at = y
>>> a.updated_at
datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=<datetime.tzinfo object at 0x113ac6600>)
>>> a.save()
>>> a = Attendance.objects.last()
>>> a.updated_at
datetime.datetime(2018, 8, 11, 13, 21, 2, 38046, tzinfo=<UTC>)

i got this to work

import datetime
import pytz

time_zone = pytz.timezone('Asia/Kuala_Lumpur')

# get naive date
date = datetime.datetime.strptime("28/07/2018", '%d/%m/%Y').date()
# get naive time
time = datetime.time(12, 30)
# combite to datetime
date_time = datetime.datetime.combine(date, time)
# make time zone aware
date_time = time_zone.localize(date_time)

# convert to UTC
utc_date_time = date_time.astimezone(pytz.utc)
# get time
utc_time = utc_date_time.time()

You don't. Django's DateTimeField is stored as Postgresql's datetimetz type. The datetimetz type doesn't store any timezone information. It is stored as UTC time and when you do SELECTs it displays it according to timezone defined in DB settings.

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