0

I have to deal with a Pandas DataFrame that can be composed by different datetime columns (they can vary, I can have 0..N datetime cols). I know that each datetime column timezone is UTC and I need to convert their data to another timezone. If I do as follows:

df['a_datetime_column'].dt.tz_localize('UTC').dt.tz_convert('my_timezone') 

it works but I need to know in advance the datetime column names (ok, I could get them in some way).

Is there a specific way to do this conversion on all the DataFrame at once independently from the composition of its columns?

3
  • 2
    What do you have when you print df.dtypes? Can you filter those with datetime type from there? Commented Feb 19, 2020 at 14:51
  • For the datetime cols I have datetime64[ns] Commented Feb 19, 2020 at 14:52
  • 1
    then you can simply loop over the columns with type datetime64[ns] Commented Feb 19, 2020 at 14:53

2 Answers 2

1

You can loop over the columns which have datetime type:

for col,dtyp in df.dtypes.iteritems():
    if dtyp == 'datetime64[ns]':
        df[col] = df[col].dt.tz_localize('UTC').dt.tz_convert('my_timezone') 
Sign up to request clarification or add additional context in comments.

Comments

1

Check out select_dtypes, you can use it to select only the datetime64[ns] columns and apply your tz_convert to those:

df.select_dtypes(inlcude=["datetime64[ns]"]).dt.tz_localize('UTC').dt.tz_convert('my_timezone') 

3 Comments

Does this require starting data being tz aware?
What do you mean? If they are of type datetime64[ns] I assume they have some sort of timezone no?
For the selection part, no.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.