How can I remove a pytz timezone from a datetime object? How can I remove a pytz timezone from a datetime object? python python

How can I remove a pytz timezone from a datetime object?


To remove a timezone (tzinfo) from a datetime object:

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

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <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)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

############################################################################### 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 naivedbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3# compare datetimes that are both aware or both naive work howeverdbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True