The Pandas DataFrame function tz_localize() used to localize tz-naive index of a Series or DataFrame to target time zone. It returns either Series DataFrame of same type as the source object.
1 DataFrame.tz_localize(tz, axis = 0, level = None, copy = None, ambiguous = 'raise', nonexistent = 'raise')
tz : It is string or tzinfo that specifies the time zone to localize. If specified value is None, it will remove the time zone information and preserve local time.
axis : It can be either string or an integer that specifies the axis. It can be 0 or index, 1 or columns. If not specified the default value will be 0.
level : It is an integer or string that specifies the localize a level, if axis is MultiIndex, otherwise None.
copy : It is a boolean value that determine whether to create copy of the underlying data or not. If not specified the default value will be 0.
ambiguous : It is either infer, boolean array or NaT, it determine when clocks moved backward due to DST, ambiguous times may arise.
1. | infer : It will attempt to infer fall dst-transition hours based on order |
2. | bool-ndarray : If an array element is True that signifies a DST time, False designates a non-DST time |
3. | NaT : It will return NaT where there are ambiguous times |
nonexistent : It is string that specifies a nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
1. | shift_forward : It will shift the nonexistent time forward to the closest existing time |
2. | shift_backward : It will shift the nonexistent time backward to the closest existing time |
3. | NaT : It will return NaT where there are nonexistent times |
4. | timedelta : An objects that will shift nonexistent times by the timedelta |
5. | raise : It will raise an NonExistentTimeError if there are nonexistent times. |
1 import pandas as pd
2 import numpy as np
3
4 indx = pd.DatetimeIndex(['2022-09-20 04:30:00'])
5 series = pd.Series([1], index = indx)
6
7 res = series.tz_localize('CET')
8 print('The converted time zone is :')
9 print(res)
In the above example, an index is created by passing an array of datetime. A series object is created by passing an array and index. A tz_localize() function is called by timezone that localize and assign result to the variable that will be printed on console.
1 The converted time zone is :
2 2022-09-20 04:30:00+02:00 1
3 dtype: int64
tz_localize() with None
1 import pandas as pd
2 import numpy as np
3
4 indx = pd.DatetimeIndex(['2022-09-20 04:30:00'])
5 series = pd.Series([1], index = indx)
6
7 res = series.tz_localize(None)
8 print('The converted time zone is :')
9 print(res)
In the above example, a tz_localize() function is called by passing a None to convert to tz-naive index and preserve local time localize and assign result to the variable that will be printed on console.
1 The converted time zone is :
2 2022-09-20 04:30:00 1
3 dtype: int64
Related options for your search