Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip timezone info in pandas

Tags:

python

pandas

I have been struggling with removing the time zone info from a column in a pandas dataframe. I have checked the following question, but it does not work for me:

Can I export pandas DataFrame to Excel stripping tzinfo?

I used tz_localize to assign a timezone to a datetime object, because I need to convert to another timezone using tz_convert. This adds an UTC offset, in the way "-06:00". I need to get rid of this offset, because it results in an error when I try to export the dataframe to Excel.

Actual output

2015-12-01 00:00:00-06:00 

Desired output

2015-12-01 00:00:00 

I have tried to get the characters I want using the str() method, but it seems the result of tz_localize is not a string. My solution so far is to export the dataframe to csv, read the file, and to use the str() method to get the characters I want.

Is there an easier solution?

like image 889
Ernesto561 Avatar asked Dec 29 '15 07:12

Ernesto561


People also ask

How do I get rid of pandas time zone?

tz_localize(None) method can be applied to the dataframe column to remove the timezone information.

How do I remove the timezone from a datetime string in Python?

To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.

How do I remove timezone from datetime?

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.

How do I strip text in pandas?

strip() function is used to remove leading and trailing characters. Strip whitespaces (including newlines) or a set of specified characters from each string in the Series/Index from left and right sides. Equivalent to str. strip().


2 Answers

If your series contains only datetimes, then you can do:

my_series.dt.tz_localize(None)

This will remove the timezone information ( it will not change the time) and return a series of naive local times, which can be exported to excel using to_excel() for example.

like image 150
Diego Mora Cespedes Avatar answered Oct 07 '22 22:10

Diego Mora Cespedes


Maybe help strip last 6 chars:

print df                     datetime 0  2015-12-01 00:00:00-06:00 1  2015-12-01 00:00:00-06:00 2  2015-12-01 00:00:00-06:00  df['datetime'] = df['datetime'].astype(str).str[:-6] print df               datetime 0  2015-12-01 00:00:00 1  2015-12-01 00:00:00 2  2015-12-01 00:00:00 
like image 39
jezrael Avatar answered Oct 07 '22 23:10

jezrael