当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Adding and returning UTC time using PYTZ

问题描述:

When I add an order to my DB, I would like to include the time as UTC.

ts = time.time()

utc = pytz.utc

orderDateUTC = datetime.utcfromtimestamp(ts).replace(tzinfo=utc)

return add_order_to_db(tableID, userID, restaurantID, orderDateUTC, orderCost, orderStatus, orderItems)

When I add the date to the DB, I add it as UTC and then try and convert it back to local time just prior to returning it to the user.

add_order_to_db(...)

def add_order_to_db(tableID, userID, restaurantID, orderDateUTC, orderCost, orderStatus, orderItems):

receivedOrder = ORDER(tableID, userID, restaurantID, orderDateUTC, orderCost, orderStatus)

with contextlib.closing(DBSession()) as session:

try:

session.add(receivedOrder)

session.commit()

except exc.SQLAlchemyError, error:

session.rollback()

raise_database_error(error)

else:

au_tz = timezone('Australia/Sydney')

au_dt = au_tz.normalize(orderDateUTC.astimezone(au_tz))

receivedOrder.ORDERSDATE = au_dt

order = Order(receivedOrder, 'true')

return jsonify(data=order.serialize())

serialize()

 def serialize(self):

return {

'orderDate' : self.ORDERSDATE

}

ORDERSDATE is defined as:

ORDERSDATE = Column(DateTime, nullable=False)

The issue is that the time is not being converted back properly.

The returned output and the data in the DB is: orderDate: "Mon, 06 Apr 2015 01:13:00 GMT"

However I need the returned output to be orderDate: "Mon, 06 Apr 2015 11:13:00 GMT"

I find that if I return return str(au_dt), I get the correct output but in a different form: 2015-04-06 11:13:37.461000+10:00

网友答案:

However I need the returned output to be orderDate: "Mon, 06 Apr 2015 11:13:00 GMT"

It is incorrect. You don't need it if the following is true:

both

The returned output and the data in the DB is: orderDate: "Mon, 06 Apr 2015 01:13:00 GMT"

and

I find that if I return return str(au_dt), I get the correct output but in a different form: 2015-04-06 11:13:37.461000+10:00

are the same time:

local time = utc time + utc offset
     11:13 =    01:13 + 10
分享给朋友:
您可能感兴趣的文章:
随机阅读: