test_tz_localize.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from datetime import timezone
  2. import numpy as np
  3. import pytest
  4. from pandas import (
  5. DataFrame,
  6. Series,
  7. date_range,
  8. )
  9. import pandas._testing as tm
  10. class TestTZLocalize:
  11. # See also:
  12. # test_tz_convert_and_localize in test_tz_convert
  13. def test_tz_localize(self, frame_or_series):
  14. rng = date_range("1/1/2011", periods=100, freq="H")
  15. obj = DataFrame({"a": 1}, index=rng)
  16. obj = tm.get_obj(obj, frame_or_series)
  17. result = obj.tz_localize("utc")
  18. expected = DataFrame({"a": 1}, rng.tz_localize("UTC"))
  19. expected = tm.get_obj(expected, frame_or_series)
  20. assert result.index.tz is timezone.utc
  21. tm.assert_equal(result, expected)
  22. def test_tz_localize_axis1(self):
  23. rng = date_range("1/1/2011", periods=100, freq="H")
  24. df = DataFrame({"a": 1}, index=rng)
  25. df = df.T
  26. result = df.tz_localize("utc", axis=1)
  27. assert result.columns.tz is timezone.utc
  28. expected = DataFrame({"a": 1}, rng.tz_localize("UTC"))
  29. tm.assert_frame_equal(result, expected.T)
  30. def test_tz_localize_naive(self, frame_or_series):
  31. # Can't localize if already tz-aware
  32. rng = date_range("1/1/2011", periods=100, freq="H", tz="utc")
  33. ts = Series(1, index=rng)
  34. ts = frame_or_series(ts)
  35. with pytest.raises(TypeError, match="Already tz-aware"):
  36. ts.tz_localize("US/Eastern")
  37. @pytest.mark.parametrize("copy", [True, False])
  38. def test_tz_localize_copy_inplace_mutate(self, copy, frame_or_series):
  39. # GH#6326
  40. obj = frame_or_series(
  41. np.arange(0, 5), index=date_range("20131027", periods=5, freq="1H", tz=None)
  42. )
  43. orig = obj.copy()
  44. result = obj.tz_localize("UTC", copy=copy)
  45. expected = frame_or_series(
  46. np.arange(0, 5),
  47. index=date_range("20131027", periods=5, freq="1H", tz="UTC"),
  48. )
  49. tm.assert_equal(result, expected)
  50. tm.assert_equal(obj, orig)
  51. assert result.index is not obj.index
  52. assert result is not obj