python - 如何在Python中转换为UTC后完全删除tzinfo?

标签 python google-app-engine datetime pytz python-dateutil

我遇到了这个确切的issue ,而且我不知道如何在我的案例中实现解决方案。

吉多说

The solution is to remove the tzinfo completely from the time after converting to UTC.

这是我尝试过的:

        date_time = parser.parse(i.pubDate.text)
        news.publication_date = date_time.replace(tzinfo=None).date()

我得到了同样的错误:

NotImplementedError: DatetimeProperty publication_date_time can only support UTC. Please derive a new Property to support alternative timezones.

所以看来我必须先将日期转换为 UTC。但我的研究失败了。

我遇到了这个solution :

建议的解决方案是这样的:

def date_time_to_utc(date_time):
        tz = pytz.timezone('???')
        return tz.normalize(tz.localize(date_time)).astimezone(pytz.utc)

但我没有时区。我正在从 html 源中抓取日期。所以时区实际上可以来自世界任何地方。是否没有简单可靠的方法将日期时间转换为 UTC? 我可以使用 dateutil 和 pytz 来实现这一点。非常感谢。

更新 这真是漫长的一天。我误读了堆栈跟踪。然而这个问题仍然有效。

date_time = (datetime}2015-01-13 18:13:26+00:00
news.publication_date_time = date_time

这导致了崩溃。看来通过这样做,我通过了单元测试:

news.publication_date_time = date_time.replace(tzinfo=None)

这是将 GMT 0 日期时间转换为 UTC 日期时间的正确方法吗?或者实际上是 UTC 的任何时区?

最佳答案

Is this the correct way converting a GMT 0 datetime to UTC datetime? Or in fact any timezone to UTC?

如果aware日期时间对象已经采用UTC (+0000)格式,则您的公式有效:

naive_utc = aware_utc.replace(tzinfo=None)

其中 aware_utc 是一个时区感知的日期时间对象,表示 UTC 时间。

但是如果aware日期时间对象不是UTC;它失败。在一般情况下,您应该考虑(可能)非零 UTC 偏移量:

assert aware.tzinfo is not None and aware.utcoffset() is not None
# local time = utc time + utc offset (by definition)
# -> utc = local - offset
naive_utc = aware.replace(tzinfo=None) - aware.utcoffset()

其中aware是任意时区中的时区感知日期时间对象。

<小时/>

But I don't have the timezone. I am scraping the date from a html source. So the timezone could really be from anywhere in the world. Is there no easy and reliable way to convert a date time to UTC? I could use both dateutil and pytz to achieve this. Many Thanks.

没有。 dateutilpytz 不会帮助您,除非日期字符串本身包含时区(或至少包含其 utc 偏移量)。

记住:总是中午某个地方在地球上,即,如果您从地球上不同的地方收集日期/时间字符串,那么您无法比较它们,除非您附加相应的时区。您无法将其转换为 UTC,如果您不知道日期的源时区,则无法获取有效的 POSIX 时间戳。

关于python - 如何在Python中转换为UTC后完全删除tzinfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973478/

相关文章:

python - 如何使用字典中的键查找值

python - 需要可见元素的 xpath 定位器

ruby - DateTime 序列化和反序列化

python - 格式为 '%' datetime.strptime 的错误指令

python - 如何组合日期和时间?

python - 使用Python将文件上传到S3(保留原始文件夹结构)并具有正确的MIME类型

python - 从数据库查询填充嵌套字典

java - 具有非默认应用引擎服务的 Google Cloud Endpoints v2 自定义域

.htaccess - Google App-Engine 按国家/地区阻止传入流量?

python - 如何在 GAE 中使用烧杯