简体   繁体   English

如何将日期时间从特定时区转换为UTC? Django DateTimeField

[英]how to convert datetime from certain timezone to UTC ? django DateTimeField

I am having trouble dealing with dealing with DateTimeField field. 我在处理DateTimeField字段时遇到麻烦。

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 我想将“ y”转换为UTC,以便将其保存到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. Django的DateTimeField存储为Postgresql的datetimetz类型。 The datetimetz type doesn't store any timezone information. datetimetz类型不存储任何时区信息。 It is stored as UTC time and when you do SELECTs it displays it according to timezone defined in DB settings. 它存储为UTC时间,当您执行SELECT时,它将根据数据库设置中定义的时区显示它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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