python – 如何从日期时间对象中删除pytz时区?
作者:互联网
有没有一种简单的方法从pytz日期时间对象中删除时区?
例如在此示例中从dt_tz重建dt:
>>> 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>)
解决方法:
要从datetime对象中删除时区(tzinfo):
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
如果您使用的是像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类型的时区.所以当你给它一个datetime.datetime对象插入数据库时,使用像sqlalchemy这样的ORM就会删除时区.解决方案是将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
标签:pytz,python,timezone 来源: https://codeday.me/bug/20191003/1851288.html