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 DjangoThis 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
最满意答案
更新以在每个名称的末尾添加_下划线。 看起来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;
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;
相关问答
更多-
更新以在每个名称的末尾添加_下划线。 看起来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 ...
-
创建后的变量(Variables in After Create)[2021-08-13]
您只需在self上调用适当的访问器方法: def make_track create_track(:user_id => self.user) end You just call the appropriate accessor method on self: def make_track create_track(:user_id => self.user) end -
将两个变量的值组合在一起以使用r创建新变量(combining values of two variables together to create a new variable using r)[2021-11-24]
如果您的数据框被称为x只需将它们粘贴在一起(强制转换为字符),然后转换为数字 x$pf <- as.numeric(paste(x$pgrp, x$fos, sep = "")) (不要使用“数据”作为名称,这是一个功能。) If your dataframe is called x just paste them together (coerces to character) and then convert to numeric x$pf <- as.numeric(paste(x$pgrp, x$f ... -
为具有特定值的数据帧中的每个变量创建虚拟指标(create dummy indicator for each variable in a data frame with specific values)[2023-12-22]
你可以使用这样的基础R解决方案: transform(df,I=ifelse(df<0|df==999,1,0)) at Bc I.at I.Bc 1 1 1 0 0 2 -9 -2 1 1 3 -1 999 1 1 4 999 0 1 0 You can use a base R solution like this: transform(df,I=ifelse(df<0|df==999,1,0)) at Bc I.at ... -
使用变量而不是值(Using variables instead of values)[2022-06-17]
这些结果应该与您的Select Case相匹配,但您可以通过任何利率或罚息。 导入System.Math。 测试你的Select Case。 Private Function Calculate(ByVal Duration As Integer, InterestRate As Double, PenaltyRate As Double) As Double Dim Rate As Double Dim Multiplier As Integer = CInt(Math.C ... -
我知道在R中使用for循环可能是禁忌,但我试过了,它运行良好。 for (i in length(DF$Col2)) { DF$Col3[i] <- Char[DF$Col2[i]] } 这足够吗? 我认为你也可以unique(DF$Col2)或levels(factor(DF$Col2)) 也许虽然我误解了你的问题。 I know it may be taboo to use for loops in R, but I tried this out and it worked well. for ...
-
使用json_decode($getcart, true); 。 这里json_decode()中的 true参数将JSON转换为数组。 如果没有true参数,它将转换为object array() 。 $getcart = '[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]'; $arr = json_decode($getcart, ...
-
变量矩阵NumPy的值(Values of Variables Matrix NumPy)[2022-03-10]
你可以做: M = np.matrix([[x, y], [w, z]]) # or A = np.array([[x, y], [w, z]]) 我也包括了数组,因为我建议使用数组而不是矩阵。 虽然一开始矩阵似乎是一个好主意(或者至少它们对我来说是这样),但是通过使用数组你可以避免很多麻烦。 以下是两者的比较,可帮助您确定哪种适合您。 我能想到的数组的唯一缺点是矩阵乘法运算不那么漂亮: # With an array the matrix multiply like this matrix_produ ... -
data.frame(Fruit = c('Apple', 'Banana'), How_many = c(Apple, Banana)) # Fruit How_many #1 Apple 5 #2 Banana 10 data.frame(Fruit = c('Apple', 'Banana'), How_many = c(Apple, Banana)) # Fruit How_many #1 Apple 5 #2 Banana 10
-
根据现有变量的值创建一个新的指标变量(create a new indicator variable based on values of existing variables)[2023-11-27]
以下是使用ifelse语句的基本R的方法。 ifelse(rowSums(d1[5:10]) > 1, 8, ifelse(rowSums(d1[5:10]) == 0, 0, max.col(d1[5:10]))) #1 2 3 4 5 6 #8 3 8 8 8 8 Here is an approach with base R using an ifelse statement. ifelse(rowSums(d1[5:10]) > 1, 8, ifelse(r ...