首页 \ 问答 \ Django datetimefield可识别时区的CET(Django datetimefield timezone aware CET)

Django datetimefield可识别时区的CET(Django datetimefield timezone aware CET)

我看到这个帖子是Django在将它保存到数据库时会破坏时区感知的DateTimeField? 但它特别使用pytz和mysql,以及不使用pytz和使用SQLite的地方(因为它可能会产生影响)。

我有以下模型

class ScheduleItem(models.Model):
    work_date = models.DateTimeField('Work date')

我插入数据如下:

from isoweek import Week
from dateutil import parser
from django.utils import timezone

def foo()
    year = 2016 #hardcoded for example purpose
    wknr = 2 #hardcoded for example purpose
    dateObj = parser.parse(Week(year, wknr).day(0).isoformat() + " 00:00:00")
    print(dateObj) # 2016-01-11 00:00:00 as expected
    final = timezone.make_aware(dateObj)
    print(final) # 2016-01-11 00:00:00+01:00 as expected
    return final


workdate = foo()
si = ScheduleItem(work_date=workdate)
si.save()

打印语句给我正确的输出,但是一旦我查看数据库(SQLite),我看到2016-01-10 23:00:00

我的Django设置说

TIME_ZONE = 'CET'
USE_TZ = True

检索我得到的数据:

datetime.datetime(2016, 1, 10, 23, 0, tzinfo=<UTC>)

为什么它以另一种格式存储数据,然后我指定,为什么如果Django设置为时区感知,我是否会收到UTC时区? 我的意思是在插入日期时间对象前说: datetime.datetime(2016, 1, 11, 0, 0, tzinfo=<DstTzInfo 'CET' CET+1:00:00 STD>)

更新 -

同时,我通过在数据库中设置TIME_ZONE找到了一个解决方法,如此处的Django文档中所述。 这给了我数据库中正确的时区/日期,但根据该文档,我不需要它,因为我的数据库由Django管理

这允许与存储日期时间的第三方数据库在本地时间而不是UTC进行交互。 为避免出现DST更改的问题,您不应为由Django管理的数据库设置此选项。

我仍然不清楚为什么Django在将数据存储在数据库中时将具有CET时区的日期时间对象转换为UTC,但在检索时还不够智能以将其转换回CET。


I saw this post Is Django corrupting timezone-aware DateTimeField when saving it to the Database? but it specifically uses pytz and mysql and what not where I don't use pytz and use SQLite (incase it might have an impact).

I have the following model

class ScheduleItem(models.Model):
    work_date = models.DateTimeField('Work date')

And I insert data as follows:

from isoweek import Week
from dateutil import parser
from django.utils import timezone

def foo()
    year = 2016 #hardcoded for example purpose
    wknr = 2 #hardcoded for example purpose
    dateObj = parser.parse(Week(year, wknr).day(0).isoformat() + " 00:00:00")
    print(dateObj) # 2016-01-11 00:00:00 as expected
    final = timezone.make_aware(dateObj)
    print(final) # 2016-01-11 00:00:00+01:00 as expected
    return final


workdate = foo()
si = ScheduleItem(work_date=workdate)
si.save()

The print statements give me the right output, however once I look in the database (SQLite) I see 2016-01-10 23:00:00

My django settings say

TIME_ZONE = 'CET'
USE_TZ = True

Retrieving the data I get:

datetime.datetime(2016, 1, 10, 23, 0, tzinfo=<UTC>)

Why is it storing the data in another format then I specify and why if Django is set to be timezone aware do I get a UTC timezone back? I mean before insertion the datetime object says: datetime.datetime(2016, 1, 11, 0, 0, tzinfo=<DstTzInfo 'CET' CET+1:00:00 STD>)

update -

I found a work around in the meantime by setting TIME_ZONE on the database as described in the Django documentation here. This gives me the right timezone/date in the database, but according to that documentation I shouldn't need it because my DB is managed by Django

This allows interacting with third-party databases that store datetimes in local time rather than UTC. To avoid issues around DST changes, you shouldn’t set this option for databases managed by Django.

It is still unclear to me why Django does convert a datetime object with a CET timezone to UTC when storing it in the database, but isn't smart enough to convert it back to CET when retrieving.


原文:https://stackoverflow.com/questions/35084164
更新时间:2023-12-28 18:12

最满意答案

更新以在每个名称的末尾添加_下划线。 看起来PROC TRANSREG没有选项在变量名和类变量的值之间加上下划线,所以我们可以只进行临时重命名。 创建重命名name = newname对以将类变量重命名为以下划线结尾并重命名它们。 CAT函数和SQL转换为宏变量。

data have;
   call streaminit(1234);
   do caseID = 1 to 1e4;
      fumert1 = rand('table',.2,.2,.2) - 1;
      sex = first(substrn('MF',rand('table',.5),1));
      output;
      end;
   stop;
   run;
%let class=sex fumert1;
proc transpose data=have(obs=0) out=vnames;
   var &class;
   run;
proc print;
   run;
proc sql noprint;
   select catx('=',_name_,cats(_name_,'_')), catx('=',cats(_name_,'_'),_name_), cats(_name_,'_')
      into :rename1 separated by ' ', :rename2 separated by ' ', :class2 separated by ' '
      from vnames;
   quit;
%put NOTE: &=rename1;
%put NOTE: &=rename2;
%put NOTE: &=class2;
proc transreg data=have(rename=(&rename1));
   model class(&class2 / zero=none);
   id caseid;
   output out=design(drop=_: inter: rename=(&rename2)) design;
   run;
%put NOTE: _TRGIND(&_trgindn)=&_trgind;

在此处输入图像描述


首先尝试:看看你提供的代码和Joe的输出我真的不明白对格式的需求。 在我看来,你只想为类变量列表创建虚拟变量。 这可以通过TRANSREG完成。

data have;
   call streaminit(1234);
   do caseID = 1 to 1e4;
      fumert1 = rand('table',.2,.2,.2) - 1;
      sex = first(substrn('MF',rand('table',.5),1));
      output;
      end;
   stop;
   run;

proc transreg data=have;
   model class(sex fumert1 / zero=none);
   id caseid;
   output out=design(drop=_: inter:) design;
   run;
proc contents;
   run;
proc print data=design(obs=40);
   run;

在此处输入图像描述


Update to add an _ underscore to the end of each name. It looks like there is not option for PROC TRANSREG to put an underscore between the variable name and the value of the class variable so we can just do a temporary rename. Create rename name=newname pairs to rename class variable to end in underscore and to rename them back. CAT functions and SQL into macro variables.

data have;
   call streaminit(1234);
   do caseID = 1 to 1e4;
      fumert1 = rand('table',.2,.2,.2) - 1;
      sex = first(substrn('MF',rand('table',.5),1));
      output;
      end;
   stop;
   run;
%let class=sex fumert1;
proc transpose data=have(obs=0) out=vnames;
   var &class;
   run;
proc print;
   run;
proc sql noprint;
   select catx('=',_name_,cats(_name_,'_')), catx('=',cats(_name_,'_'),_name_), cats(_name_,'_')
      into :rename1 separated by ' ', :rename2 separated by ' ', :class2 separated by ' '
      from vnames;
   quit;
%put NOTE: &=rename1;
%put NOTE: &=rename2;
%put NOTE: &=class2;
proc transreg data=have(rename=(&rename1));
   model class(&class2 / zero=none);
   id caseid;
   output out=design(drop=_: inter: rename=(&rename2)) design;
   run;
%put NOTE: _TRGIND(&_trgindn)=&_trgind;

enter image description here


First try: Looking at the code you supplied and the output from Joe's I don't really understand the need for the formats. It looks to me like you just want to create dummies for a list of class variables. That can be done with TRANSREG.

data have;
   call streaminit(1234);
   do caseID = 1 to 1e4;
      fumert1 = rand('table',.2,.2,.2) - 1;
      sex = first(substrn('MF',rand('table',.5),1));
      output;
      end;
   stop;
   run;

proc transreg data=have;
   model class(sex fumert1 / zero=none);
   id caseid;
   output out=design(drop=_: inter:) design;
   run;
proc contents;
   run;
proc print data=design(obs=40);
   run;

enter image description here

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)