Python:如何获取“timezone aware”的datetime.today()值? [英] Python: How to get a value of datetime.today() that is "timezone aware"?

查看:124
本文介绍了Python:如何获取“timezone aware”的datetime.today()值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 datetime.today()的值中减去一个日期值,以计算一段时间以前的日期值。但是它抱怨:

  TypeError:不能减去offset-naive和offset-aware datetimes 

datetime.today()似乎不是时区知道,而我的其他日期值是。如何获取时区知道的 datetime.today()的值?现在它给了我当地时间,这恰好是PST,即UTC-8小时。最糟糕的情况是,有没有办法我可以手动输入一个时区值到由 datetime.today()返回的 datetime 对象并将其设置为UTC-8?当然,理想的解决方案是让它自动知道时区。

解决方案

在标准库中,没有交叉-platform方式来创建感知时区,而不需要创建自己的时区类。



在Windows上,有 win32timezone.utcnow(),但这是pywin32的一部分。我宁愿建议使用 pytz库,该库具有大多数时区的最新数据库。 / p>

使用本地时区可能非常棘手(阅读pytz文档!),因此您可能希望在整个应用程序中使用UTC。您可以这样获取当前的日期/时间:

 从datetime导入datetime $ t 
$ b datetime .utcnow()。replace(tzinfo = pytz.utc)

注意 datetime.today() datetime.now()返回本地时间,而不是UTC时间,所以应用 .replace(tzinfo = pytz.utc)给他们是不正确的。



另一个很好的方法是:

  datetime.now(pytz.utc)

这是一个更短的一点。


I am trying to subtract one date value from the value of datetime.today() to calculate how long ago something was. But it complains:

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

The value datetime.today() doesn't seem to be "timezone aware", while my other date value is. How do I get a value of datetime.today() that is timezone aware? Right now it's giving me the time in local time, which happens to be PST, i.e. UTC-8hrs. Worst case, is there a way I can manually enter a timezone value into the datetime object returned by datetime.today() and set it to UTC-8? Of course, the ideal solution would be for it to automatically know the timezone.

解决方案

In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class.

On Windows, there's win32timezone.utcnow(), but that's part of pywin32. I would rather suggest to use the pytz library, which has an up-to-date database of most timezones.

Working with local timezones can be very tricky (read the pytz documentation!), so you may rather want to use UTC throughout your application. You can get the current date/time like so:

import pytz
from datetime import datetime
datetime.utcnow().replace(tzinfo=pytz.utc)

Mind that datetime.today() and datetime.now() return the local time, not the UTC time, so applying .replace(tzinfo=pytz.utc) to them would not be correct.

Another nice way to do it is:

datetime.now(pytz.utc)

which is a bit shorter and does the same.

这篇关于Python:如何获取“timezone aware”的datetime.today()值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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