如何从日期时间对象中删除pytz时区?


120

有没有一种简单的方法可以从pytz datetime对象中删除时区?
例如,dtdt_tz本示例中进行重构:

>>> import datetime
>>> import pytz
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2012, 6, 8, 9, 27, 32, 601000)
>>> dt_tz = pytz.utc.localize(dt)
>>> dt_tz
datetime.datetime(2012, 6, 8, 9, 27, 32, 601000, tzinfo=<UTC>)

Answers:


207

要从日期时间对象中删除时区(tzinfo):

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

如果您使用的是诸如arrow的库,则可以通过简单地将arrow对象转换为datetime对象来删除时区,然后执行与上述示例相同的操作。

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

你为什么要这样做?一个例子是mysql不支持DATETIME类型的时区。因此,使用ORM之类的sqlalchemy时,只要为datetime.datetime对象提供要插入数据库的时区,它便会删除时区。解决方案是将datetime.datetime对象转换为UTC(由于无法指定时区,因此数据库中的所有内容均为UTC),然后将其插入数据库(无论如何都删除了时区),也可以自行删除。还要注意,您不能比较datetime.datetime其中一个是时区感知而另一个是时区幼稚的对象。

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.