w3resource

Pandas Series: dt.tz_localize() function

Series.dt.tz_localize() function

The tz_localize() function is used to localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index.
This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. It does not move the time to another time zone. Time zone localization helps to switch from time zone aware to time zone unaware objects.

Syntax:

Series.dt.tz_localize(self, *args, **kwargs)
Pandas Series: dt.tz_localize() function

Parameter:

Name Description Type / Default Value Required / Optional
tz Time zone to convert timestamps to. Passing None will remove the time zone information preserving local time. str, pytz.timezone, dateutil.tz.tzfile or None Required
ambiguous When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the ambiguous parameter dictates how ambiguous times should be handled.
  • 'infer' will attempt to infer fall dst-transition hours based on order
  • bool-ndarray where True signifies a DST time, False signifies a non-DST time (note that this flag is only applicable for ambiguous times)
  • 'NaT' will return NaT where there are ambiguous times
  • 'raise' will raise an AmbiguousTimeError if there are ambiguous times
‘infer’, ‘NaT’, bool array, default ‘raise’ Required
nonexistent A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
  • 'shift_forward' will shift the nonexistent time forward to the closest existing time
  • 'shift_backward' will shift the nonexistent time backward to the closest existing time
  • 'NaT' will return NaT where there are nonexistent times
  • timedelta objects will shift nonexistent times by the timedelta
  • 'raise' will raise an NonExistentTimeError if there are nonexistent times
'shift_forward', 'shift_backward', 'NaT', timedelta, default 'raise' Required

Returns: Same type as self
Array/Index converted to the specified time zone.

Raises: TypeError
If the Datetime Array/Index is tz-aware and tz is not None.

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
tz_naive = pd.date_range('2019-03-01 09:00', periods=3)
tz_naive

Output:

DatetimeIndex(['2019-03-01 09:00:00', '2019-03-02 09:00:00',
               '2019-03-03 09:00:00'],
              dtype='datetime64[ns]', freq='D')

Example - Localize DatetimeIndex in US/Eastern time zone:

Python-Pandas Code:

import numpy as np
import pandas as pd
tz_aware = tz_naive.tz_localize(tz='US/Eastern')
tz_aware

Output:

DatetimeIndex(['2019-03-01 09:00:00-05:00', '2019-03-02 09:00:00-05:00',
               '2019-03-03 09:00:00-05:00'],
              dtype='datetime64[ns, US/Eastern]', freq='D')

Example - With the tz=None, we can remove the time zone information while keeping the local time (not converted to UTC):

Python-Pandas Code:

import numpy as np
import pandas as pd
tz_aware = tz_naive.tz_localize(tz='US/Eastern')
tz_aware.tz_localize(None)

Output:

DatetimeIndex(['2019-03-01 09:00:00', '2019-03-02 09:00:00',
               '2019-03-03 09:00:00'],
              dtype='datetime64[ns]', freq='D')

Example - In some cases, inferring the DST is impossible. In such cases, you can pass an ndarray to the ambiguous parameter to set the DST explicitly:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.to_datetime(pd.Series(['2019-10-28 01:20:00',
                              '2019-10-28 02:36:00',
                              '2019-10-28 03:46:00']))
s.dt.tz_localize('CET', ambiguous=np.array([True, True, False]))

Output:

0   2019-10-28 01:20:00+01:00
1   2019-10-28 02:36:00+01:00
2   2019-10-28 03:46:00+01:00
dtype: datetime64[ns, CET]

Previous: Series.dt.to_pydatetime() function
Next: Series.dt.tz_convert() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/pandas/series/series-dt-tz_localize.php