datetime オブジェクトからタイムゾーン (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 タイプのタイムゾーンをサポートしていません。したがって、sqlalchemy のような ORM を使用するとdatetime.datetime
、データベースに挿入するオブジェクトを指定すると、タイムゾーンが単純に削除されます。解決策は、オブジェクトを UTC に変換datetime.datetime
し (タイムゾーンを指定できないため、データベース内のすべてが 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