不能减去偏移天真和偏移感知日期时间 [英] Can't subtract offset-naive and offset-aware datetimes

查看:21
本文介绍了不能减去偏移天真和偏移感知日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PostgreSQL 中有一个时区感知 timestamptz 字段.当我从表中提取数据时,我想减去现在的时间,这样我就可以得到它的年龄.

I have a timezone aware timestamptz field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.

我遇到的问题是 datetime.datetime.now()datetime.datetime.utcnow() 似乎都返回时区不知道的时间戳,结果在我得到这个错误:

The problem I'm having is that both datetime.datetime.now() and datetime.datetime.utcnow() seem to return timezone unaware timestamps, which results in me getting this error:

TypeError: can't subtract offset-naive and offset-aware datetimes 

有没有办法避免这种情况(最好不使用第三方模块).

Is there a way to avoid this (preferably without a third-party module being used).

感谢您的建议,但是尝试调整时区似乎会给我带来错误..所以我将在 PG 中使用时区不知道的时间戳并始终使用插入:

Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:

NOW() AT TIME ZONE 'UTC'

这样我所有的时间戳默认都是 UTC(即使这样做更烦人).

That way all my timestamps are UTC by default (even though it's more annoying to do this).

推荐答案

您是否尝试过移除时区感知?

have you tried to remove the timezone awareness?

来自http://pytz.sourceforge.net/

naive = dt.replace(tzinfo=None)

可能还需要添加时区转换.

may have to add time zone conversion as well.

请注意这个答案的年龄.下面是一个涉及添加时区信息而不是在 python 3 中删除它的答案.https://stackoverflow.com/a/25662061/93380

edit: Please be aware the age of this answer. An answer involving ADDing the timezone info instead of removing it in python 3 is below. https://stackoverflow.com/a/25662061/93380

这篇关于不能减去偏移天真和偏移感知日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆