Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

python: Parse ISO 8601 times with datetime.fromisoformat.

Anders Kaseorge0fa8e93452f
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py
index ef4888fb551..e32d1a6fe42 100644
--- a/corporate/lib/stripe.py
+++ b/corporate/lib/stripe.py
@@ -5,7 +5,7 @@ import secrets
from abc import ABC, abstractmethod
from collections.abc import Callable, Generator
from dataclasses import dataclass
-from datetime import date, datetime, timedelta, timezone
+from datetime import date, datetime, time, timedelta, timezone
from decimal import Decimal
from enum import Enum, IntEnum
from functools import wraps
@@ -1417,8 +1417,11 @@ class BillingSession(ABC):
return f"Required plan tier for {self.billing_entity_display_name} set to {plan_tier_name}."
def configure_complimentary_access_plan(self, end_date_string: str) -> str:
- plan_end_date = datetime.strptime(end_date_string, "%Y-%m-%d").replace(tzinfo=timezone.utc)
- if plan_end_date.date() <= timezone_now().date():
+ plan_end_date = datetime.combine(
+ date.fromisoformat(end_date_string), time(0, 0, 0), timezone.utc
+ )
+ plan_anchor_date = timezone_now()
+ if plan_end_date <= plan_anchor_date:
raise SupportRequestError(
f"Cannot configure a complimentary access plan for {self.billing_entity_display_name} to end on {end_date_string}."
)
@@ -1429,7 +1432,6 @@ class BillingSession(ABC):
raise SupportRequestError(
f"Cannot configure a complimentary access plan for {self.billing_entity_display_name} because of current plan."
)
- plan_anchor_date = timezone_now()
if isinstance(self, RealmBillingSession):
# TODO implement a complimentary access plan/tier for Zulip Cloud.
raise SupportRequestError(
@@ -1612,8 +1614,10 @@ class BillingSession(ABC):
return success_message
def update_end_date_of_current_plan(self, end_date_string: str) -> str:
- new_end_date = datetime.strptime(end_date_string, "%Y-%m-%d").replace(tzinfo=timezone.utc)
- if new_end_date.date() <= timezone_now().date():
+ new_end_date = datetime.combine(
+ date.fromisoformat(end_date_string), time(0, 0, 0), timezone.utc
+ )
+ if new_end_date <= timezone_now():
raise SupportRequestError(
f"Cannot update current plan for {self.billing_entity_display_name} to end on {end_date_string}."
)
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py
index d584ced18a6..0657e1b7959 100644
--- a/corporate/tests/test_stripe.py
+++ b/corporate/tests/test_stripe.py
@@ -4,14 +4,14 @@ import operator
import os
import re
import sys
-import time
import typing
import uuid
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
-from datetime import datetime, timedelta, timezone
+from datetime import date, datetime, time, timedelta, timezone
from decimal import Decimal
from functools import wraps
+from time import sleep
from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, cast
from unittest import mock
from unittest.mock import MagicMock, Mock, patch
@@ -591,7 +591,7 @@ class StripeTestCase(ZulipTestCase):
raise AssertionError(
f"Did not find expected event {must_have_event} after looking for it multiple times"
)
- time.sleep(0.2)
+ sleep(0.2)
continue
for event in events_old_to_new:
@@ -6514,8 +6514,8 @@ class InvoiceTest(StripeTestCase):
billing_session = RealmBillingSession(user=hamlet, realm=realm)
next_billing_cycle = billing_session.get_next_billing_cycle(plan)
plan_end_date_string = next_billing_cycle.strftime("%Y-%m-%d")
- plan_end_date = datetime.strptime(plan_end_date_string, "%Y-%m-%d").replace(
- tzinfo=timezone.utc
+ plan_end_date = datetime.combine(
+ date.fromisoformat(plan_end_date_string), time(0, 0, 0), tzinfo=timezone.utc
)
self.logout()
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.py
index a4b1efbe5aa..9adf6450268 100644
--- a/zerver/lib/email_notifications.py
+++ b/zerver/lib/email_notifications.py
@@ -8,7 +8,7 @@ import sys
import zoneinfo
from collections import defaultdict
from dataclasses import dataclass
-from datetime import timedelta
+from datetime import datetime, timedelta
from email.headerregistry import Address
from typing import Any
@@ -195,7 +195,7 @@ def convert_time_to_local_timezone(fragment: lxml.html.HtmlElement, user: UserPr
# We expect there to always be a datetime attribute.
continue # nocoverage
try:
- dt_utc = timezone_now().strptime(datetime_str, "%Y-%m-%dT%H:%M:%S%z")
+ dt_utc = datetime.fromisoformat(datetime_str)
dt_local = dt_utc.astimezone(zoneinfo.ZoneInfo(canonicalize_timezone(user_tz)))
formatted_time = format_datetime_to_string(dt_local, user.twenty_four_hour_time)
time_elem.text = formatted_time
diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py
index 9b013280945..ea692008bc1 100644
--- a/zerver/lib/validator.py
+++ b/zerver/lib/validator.py
@@ -30,7 +30,7 @@ for any particular type of object.
from collections.abc import Collection, Container, Iterator
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import date
from typing import Any, NoReturn, TypeVar, cast, overload
import orjson
@@ -117,10 +117,7 @@ def check_date(var_name: str, val: object) -> str:
if not isinstance(val, str):
raise ValidationError(_("{var_name} is not a string").format(var_name=var_name))
try:
- if (
- datetime.strptime(val, "%Y-%m-%d").replace(tzinfo=timezone.utc).strftime("%Y-%m-%d")
- != val
- ):
+ if date.fromisoformat(val).strftime("%Y-%m-%d") != val:
raise ValidationError(_("{var_name} is not a date").format(var_name=var_name))
except ValueError:
raise ValidationError(_("{var_name} is not a date").format(var_name=var_name))
diff --git a/zerver/tests/test_custom_profile_data.py b/zerver/tests/test_custom_profile_data.py
index 2b51460428b..523b911ab57 100644
--- a/zerver/tests/test_custom_profile_data.py
+++ b/zerver/tests/test_custom_profile_data.py
@@ -797,6 +797,9 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):
self.assert_error_update_invalid_value(
field_name, "1909-3-5", f"{field_name} is not a date"
)
+ self.assert_error_update_invalid_value(
+ field_name, "19090305", f"{field_name} is not a date"
+ )
self.assert_error_update_invalid_value(field_name, [123], f"{field_name} is not a string")
def test_update_invalid_url(self) -> None: