Working datetime objects in Google App Engine
In this model
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mWEIGHT = db.IntegerProperty()
I want to do:
mWEIGHT = mCOUNT开发者_运维知识库 / mDATE0
within this for loop
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
rep=C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
# how to convert mDATE0 to integer so that I can divide:
# rep.mWEIGHT = rep.mCOUNT / rep.mDATE0
rep.put()
else:
C = COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
I asked the same question in several other forums and I got good and valuable advice but I am still unable to make this code work because I am confused about (objects, instance, datetime.datetime, seconds, second ... and so on) For instance, I thought that
mWEIGHT = mCOUNT / rep.mDATE0.second
would turn mDATE0 into seconds; but it does not, it just take the second part from 2010-11-12 18:57:27.338000
ie, 27.
And
mWEIGHT = mCOUNT / mDATE0.date
gives an type mismatch error message.
I also tried
rep.mWEIGHT = rep.mCOUNT / rep.mDATE0.toordinal()
this gives a number like 734088
but all items had the same number.
See also my previous question on the same subject.
Thank you for your help.
EDIT3
This works, thanks!
if C_RESULT:
rep = C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
utc_tuple = rep.mDATE0.utctimetuple()
# this is actually float not integer
mDATE0_integer = time.mktime(utc_tuple)
mDATE0_day = mDATE0_integer / 86400
rep.mWEIGHT = float(rep.mCOUNT / mDATE0_day)
rep.put()
EDIT2 @Constantin: I realized that numbers need to be floats:
>>> mCOUNT = 35
>>> div = mCOUNT / mDATE0
>>> div
0
>>> div = float(mCOUNT) / float(mDATE0)
>>> div
2.7140704010987625e-08
>>>
Not sure how to incorporate this to the script. Any suggestions?
EDIT
@Constantin:
For the item
C_RESULT[0] = "new item"
this is the result I get.
new item:
rep: <__main__.Rep object at 0x052186D0>
mDATE0_integer: 1289575981
rep.mCOUNT: 35
rep.mWEIGHT: 0
So
mDATE0_integer = int(time.mktime(rep.mDATE0.utctimetuple()))
works and gives the integer 1289575981
but this division
rep.mWEIGHT = rep.mCOUNT / mDATE0_integer
results in 0. Any suggestions?
This should do what you want:
import time
mWEIGHT = mCOUNT / time.mktime(mDATE0.utctimetuple())
See mktime
.
mCOUNT / mDATE0.date
fails because there is no division operator for int
and date
.
toordinal
doesn't suit you because it operates on dates and disregards time completely.
精彩评论