| 759 | |
| 760 | |
| 761 | def test_timezone(tz_env): |
| 762 | os.environ["USE_TZ"] = "True" |
| 763 | timezone._reset_timezone_cache() |
| 764 | |
| 765 | # test localtime |
| 766 | assert timezone.localtime() <= timezone.now() <= timezone.localtime() |
| 767 | utcnow = datetime.now(UTC) |
| 768 | tz_shanghai = ZoneInfo("Asia/Shanghai") |
| 769 | assert timezone.localtime(utcnow).utcoffset() == timezone.now().utcoffset() |
| 770 | localtime_shanghai = timezone.localtime(utcnow, tz_shanghai.key) |
| 771 | assert timezone.localtime(utcnow, tz_shanghai) == localtime_shanghai |
| 772 | assert localtime_shanghai.utcoffset() != timezone.localtime(utcnow, "UTC").utcoffset() |
| 773 | naive_dt = datetime.now() |
| 774 | with pytest.raises(ValueError): |
| 775 | timezone.localtime(naive_dt) |
| 776 | # test make_naive |
| 777 | assert timezone.make_naive(timezone.now()).tzinfo is None |
| 778 | with pytest.raises(ValueError): |
| 779 | timezone.make_naive(naive_dt) |
| 780 | tz_shanghai = ZoneInfo("Asia/Shanghai") |
| 781 | now_shanghai = datetime.now(tz_shanghai) |
| 782 | offset = now_shanghai.utcoffset() |
| 783 | naive_now = timezone.make_naive(utcnow, tz_shanghai.key) |
| 784 | assert (utcnow + offset).isoformat().split("+")[0] == naive_now.isoformat() |
| 785 | # test make_aware |
| 786 | with pytest.raises(ValueError): |
| 787 | timezone.make_aware(utcnow) |
| 788 | aware_now = timezone.make_aware(naive_now, tz_shanghai.key) |
| 789 | assert aware_now.utcoffset() == now_shanghai.utcoffset() |
| 790 | assert "+" in timezone.make_aware(naive_now).isoformat() |
| 791 | # test compatible with pytz |
| 792 | with contextlib.suppress(ImportError): |
| 793 | import pytz |
| 794 | |
| 795 | aware_now = timezone.make_aware(naive_now, pytz.timezone(tz_shanghai.key)) |
| 796 | assert aware_now.utcoffset() == now_shanghai.utcoffset() |
| 797 | pytz_shanghai = pytz.timezone(tz_shanghai.key) |
| 798 | assert pytz_shanghai.zone == tz_shanghai.zone == tz_shanghai.key |
| 799 | assert localtime_shanghai == timezone.localtime(utcnow, pytz_shanghai) |
| 800 | assert ( |
| 801 | localtime_shanghai.utcoffset() == timezone.localtime(timezone=pytz_shanghai).utcoffset() |
| 802 | ) |