Pandas Series: dt.tz_convert() function
Series.dt.tz_convert() function
The tz_convert() function is used to convert tz-aware Datetime Array/Index from one time zone to another.
Syntax:
Series.dt.tz_convert(self, *args, **kwargs)
Parameter:
Name | Description | Type / Default Value | Required / Optional |
---|---|---|---|
tz | Time zone for time. Corresponding timestamps would be converted to this time zone of the Datetime Array/Index. A tz of None will convert to UTC and remove the timezone information. | str, pytz.timezone, dateutil.tz.tzfile or None | Required |
Returns: Array or Index
Raises: TypeError
If Datetime Array/Index is tz-naive.
Example - With the tz parameter, you can change the DatetimeIndex to other time zones:
Python-Pandas Code:
import numpy as np
import pandas as pd
dti = pd.date_range(start='2019-08-01 09:00',
freq='H', periods=3, tz='Europe/Berlin')
dti
Output:
DatetimeIndex(['2019-08-01 09:00:00+02:00', '2019-08-01 10:00:00+02:00', '2019-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H')
Python-Pandas Code:
import numpy as np
import pandas as pd
dti = pd.date_range(start='2019-08-01 09:00',
freq='H', periods=3, tz='Europe/Berlin')
dti.tz_convert('US/Central')
Output:
DatetimeIndex(['2019-08-01 02:00:00-05:00', '2019-08-01 03:00:00-05:00', '2019-08-01 04:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')
Example - With the tz=None, we can remove the timezone (after converting to UTC if necessary):
Python-Pandas Code:
import numpy as np
import pandas as pd
dti = pd.date_range(start='2019-08-01 09:00', freq='H',
periods=3, tz='Europe/Berlin')
dti
Output:
DatetimeIndex(['2019-08-01 09:00:00+02:00', '2019-08-01 10:00:00+02:00', '2019-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H')
Python-Pandas Code:
import numpy as np
import pandas as pd
dti = pd.date_range(start='2019-08-01 09:00', freq='H',
periods=3, tz='Europe/Berlin')
dti.tz_convert(None)
Output:
DatetimeIndex(['2019-08-01 07:00:00', '2019-08-01 08:00:00', '2019-08-01 09:00:00'], dtype='datetime64[ns]', freq='H')
Previous: Series.dt.tz_localize() function
Next: Series.dt.normalize() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-dt-tz_convert.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics