若要從日期時間對象中刪除一個時區(tzinfo)將箭頭對象轉換爲日期時間對象,然後執行與上述示例相同的操作。
# <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
對象以插入數據庫時簡單地刪除時區。解決方案是將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