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: Format ISO 8601 times with isoformat.

Anders Kaseorg1fc4dd71c5a3
diff --git a/corporate/lib/activity.py b/corporate/lib/activity.py
index cb21b2a87ea..0501fd4e6ef 100644
--- a/corporate/lib/activity.py
+++ b/corporate/lib/activity.py
@@ -97,7 +97,7 @@ def dictfetchall(cursor: CursorWrapper) -> list[dict[str, Any]]:
def format_optional_datetime(date: datetime | None, display_none: bool = False) -> str:
if date:
- return date.strftime("%Y-%m-%d %H:%M")
+ return date.replace(tzinfo=None).isoformat(" ", "minutes")
elif display_none:
return "None"
else:
@@ -105,7 +105,7 @@ def format_optional_datetime(date: datetime | None, display_none: bool = False)
def format_datetime_as_date(date: datetime) -> str:
- return date.strftime("%Y-%m-%d")
+ return date.date().isoformat()
def format_none_as_zero(value: int | None) -> int:
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py
index e32d1a6fe42..63ddc667efc 100644
--- a/corporate/lib/stripe.py
+++ b/corporate/lib/stripe.py
@@ -5570,7 +5570,7 @@ def maybe_send_fixed_price_plan_renewal_reminder_email(
if plan.end_date - plan.next_invoice_date <= timedelta(days=62):
context = {
"billing_entity": billing_session.billing_entity_display_name,
- "end_date": plan.end_date.strftime("%Y-%m-%d"),
+ "end_date": plan.end_date.date().isoformat(),
"support_url": billing_session.support_url(),
"notice_reason": "fixed_price_plan_ends_soon",
}
@@ -5620,7 +5620,7 @@ def maybe_send_stale_audit_log_data_email(
context = {
"billing_entity": billing_session.billing_entity_display_name,
"support_url": billing_session.support_url(),
- "last_audit_log_update": last_audit_log_update.strftime("%Y-%m-%d"),
+ "last_audit_log_update": last_audit_log_update.date().isoformat(),
"fixed_price_plan": plan.fixed_price is not None,
"notice_reason": "stale_audit_log_data",
}
@@ -5664,7 +5664,7 @@ def check_remote_server_audit_log_data(
if last_audit_log_update is None: # nocoverage
context["last_audit_log_update"] = "Never uploaded"
else:
- context["last_audit_log_update"] = last_audit_log_update.strftime("%Y-%m-%d")
+ context["last_audit_log_update"] = last_audit_log_update.date().isoformat()
send_email(
"zerver/emails/internal_billing_notice",
to_emails=[BILLING_SUPPORT_EMAIL],
diff --git a/corporate/lib/support.py b/corporate/lib/support.py
index 749af924bc7..2647342864a 100644
--- a/corporate/lib/support.py
+++ b/corporate/lib/support.py
@@ -389,8 +389,10 @@ def get_mobile_push_data(remote_entity: RemoteZulipServer | RemoteRealm) -> Mobi
# mobile_pushes_forwarded is a CountStat with a day frequency,
# so we want to show the start of the latest day interval.
push_forwarded_interval_start = (
- latest_remote_server_push_forwarded_count.end_time - timedelta(days=1)
- ).strftime("%Y-%m-%d")
+ (latest_remote_server_push_forwarded_count.end_time - timedelta(days=1))
+ .date()
+ .isoformat()
+ )
else:
push_forwarded_interval_start = "None"
push_status = get_push_status_for_remote_request(
@@ -432,8 +434,10 @@ def get_mobile_push_data(remote_entity: RemoteZulipServer | RemoteRealm) -> Mobi
# mobile_pushes_forwarded is a CountStat with a day frequency,
# so we want to show the start of the latest day interval.
push_forwarded_interval_start = (
- latest_remote_realm_push_forwarded_count.end_time - timedelta(days=1)
- ).strftime("%Y-%m-%d")
+ (latest_remote_realm_push_forwarded_count.end_time - timedelta(days=1))
+ .date()
+ .isoformat()
+ )
else:
push_forwarded_interval_start = "None"
push_status = get_push_status_for_remote_request(remote_entity.server, remote_entity)
diff --git a/corporate/models/licenses.py b/corporate/models/licenses.py
index 12e3a459557..ce96622d7e3 100644
--- a/corporate/models/licenses.py
+++ b/corporate/models/licenses.py
@@ -41,5 +41,5 @@ class LicenseLedger(models.Model):
@override
def __str__(self) -> str:
ledger_type = "renewal" if self.is_renewal else "update"
- ledger_time = self.event_time.strftime("%Y-%m-%d %H:%M")
+ ledger_time = self.event_time.replace(tzinfo=None).isoformat(" ", "minutes")
return f"License {ledger_type}, {self.licenses} purchased, {self.licenses_at_next_renewal} next cycle, {ledger_time} (id={self.id})"
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py
index 0657e1b7959..35b1371aedf 100644
--- a/corporate/tests/test_stripe.py
+++ b/corporate/tests/test_stripe.py
@@ -6513,7 +6513,7 @@ 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_string = next_billing_cycle.date().isoformat()
plan_end_date = datetime.combine(
date.fromisoformat(plan_end_date_string), time(0, 0, 0), tzinfo=timezone.utc
)
@@ -8170,7 +8170,7 @@ class TestRemoteRealmBillingFlow(StripeTestCase, RemoteRealmBillingTestCase):
annual_fixed_price = 1200
# Configure complimentary access plan
- complimentary_access_plan_end = self.next_year.strftime("%Y-%m-%d")
+ complimentary_access_plan_end = self.next_year.date().isoformat()
billing_session = RemoteRealmBillingSession(remote_realm=self.remote_realm)
support_request = SupportViewRequest(
support_type=SupportType.configure_complimentary_access_plan,
@@ -8713,7 +8713,7 @@ class TestRemoteRealmBillingFlow(StripeTestCase, RemoteRealmBillingTestCase):
message.body,
)
self.assertEqual(
- f"Fixed-price plan for {billing_entity} ends on {end_date.strftime('%Y-%m-%d')}",
+ f"Fixed-price plan for {billing_entity} ends on {end_date.date().isoformat()}",
message.subject,
)
@@ -9114,9 +9114,7 @@ class TestRemoteRealmBillingFlow(StripeTestCase, RemoteRealmBillingTestCase):
"Unable to verify current licenses in use, which delays invoicing for this customer.",
message.body,
)
- self.assertIn(
- f"Last data upload: {last_audit_log_update.strftime('%Y-%m-%d')}", message.body
- )
+ self.assertIn(f"Last data upload: {last_audit_log_update.date().isoformat()}", message.body)
# Cron runs again, don't send another email to Zulip team.
invoice_plans_as_needed(self.next_month + timedelta(days=1))
@@ -10187,9 +10185,7 @@ class TestRemoteServerBillingFlow(StripeTestCase, RemoteServerTestCase):
"Unable to verify current licenses in use, but invoicing not delayed because customer has a fixed-price plan.",
message.body,
)
- self.assertIn(
- f"Last data upload: {last_audit_log_update.strftime('%Y-%m-%d')}", message.body
- )
+ self.assertIn(f"Last data upload: {last_audit_log_update.date().isoformat()}", message.body)
# Audit log data is up-to-date when the plan is next invoiced.
with time_machine.travel(updated_invoice_date, tick=False):
@@ -10701,9 +10697,7 @@ class TestRemoteServerBillingFlow(StripeTestCase, RemoteServerTestCase):
"Unable to verify current licenses in use, which delays invoicing for this customer.",
message.body,
)
- self.assertIn(
- f"Last data upload: {last_audit_log_upload.strftime('%Y-%m-%d')}", message.body
- )
+ self.assertIn(f"Last data upload: {last_audit_log_upload.date().isoformat()}", message.body)
# Cron runs again, don't send another email to Zulip team.
invoice_plans_as_needed(self.next_month + timedelta(days=1))
diff --git a/corporate/tests/test_support_views.py b/corporate/tests/test_support_views.py
index 3f4431ff13c..5bc38a28de5 100644
--- a/corporate/tests/test_support_views.py
+++ b/corporate/tests/test_support_views.py
@@ -1751,7 +1751,7 @@ class TestSupportEndpoint(ZulipTestCase):
)
billing_session = RealmBillingSession(user=iago, realm=lear_realm, support_session=True)
- next_billing_cycle = billing_session.get_next_billing_cycle(plan).strftime("%Y-%m-%d")
+ next_billing_cycle = billing_session.get_next_billing_cycle(plan).date().isoformat()
with time_machine.travel(datetime(2016, 1, 3, tzinfo=timezone.utc), tick=False):
result = self.client_post(
"/activity/support",
diff --git a/corporate/views/installation_activity.py b/corporate/views/installation_activity.py
index fd3917274b0..0b4e20a4715 100644
--- a/corporate/views/installation_activity.py
+++ b/corporate/views/installation_activity.py
@@ -328,7 +328,7 @@ def realm_summary_table(export: bool) -> str:
rows=rows,
totals=total_row,
num_active_sites=num_active_sites,
- utctime=now.strftime("%Y-%m-%d %H:%M %Z"),
+ utctime=now.isoformat(" ", "minutes"),
billing_enabled=settings.BILLING_ENABLED,
export=export,
),
diff --git a/templates/corporate/support/current_plan_forms_support.html b/templates/corporate/support/current_plan_forms_support.html
index 12732f89b68..551bd74b7c9 100644
--- a/templates/corporate/support/current_plan_forms_support.html
+++ b/templates/corporate/support/current_plan_forms_support.html
@@ -15,7 +15,7 @@
{{ csrf_input }}
<input type="hidden" name="{{ remote_type }}" value="{{ remote_id }}" />
<input type="date" name="plan_end_date" {% if current_plan.end_date %}
- value="{{ current_plan.end_date.strftime('%Y-%m-%d') }}" {% endif %} required />
+ value="{{ current_plan.end_date.date().isoformat() }}" {% endif %} required />
<button type="submit" class="support-submit-button">Update</button>
</form>
{% endif %}
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.py
index 4545eb18f2f..5b5af85fa6c 100644
--- a/zerver/data_import/slack.py
+++ b/zerver/data_import/slack.py
@@ -986,7 +986,7 @@ def get_zulip_thread_topic_name(
e.g "2024-05-22 Hello this is a long message that will be c… (1)"
"""
- thread_date = thread_ts.strftime(r"%Y-%m-%d")
+ thread_date = thread_ts.date().isoformat()
# Truncate
truncated_zulip_topic_name = truncate_content(
diff --git a/zerver/lib/debug.py b/zerver/lib/debug.py
index 1ff1200ea11..4286d52e97d 100644
--- a/zerver/lib/debug.py
+++ b/zerver/lib/debug.py
@@ -46,7 +46,9 @@ def tracemalloc_dump() -> None:
logger.warning("pid %s: tracemalloc off, nothing to dump", os.getpid())
return
# Despite our name for it, `timezone_now` always deals in UTC.
- basename = "snap.{}.{}".format(os.getpid(), timezone_now().strftime("%F-%T"))
+ basename = "snap.{}.{}".format(
+ os.getpid(), timezone_now().replace(tzinfo=None).isoformat("-", "seconds")
+ )
path = os.path.join(settings.TRACEMALLOC_DUMP_DIR, basename)
os.makedirs(settings.TRACEMALLOC_DUMP_DIR, exist_ok=True)
diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py
index ea692008bc1..9768a1ae0cc 100644
--- a/zerver/lib/validator.py
+++ b/zerver/lib/validator.py
@@ -117,7 +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 date.fromisoformat(val).strftime("%Y-%m-%d") != val:
+ if date.fromisoformat(val).isoformat() != 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/management/commands/export_search.py b/zerver/management/commands/export_search.py
index 91e6cbf8acd..376db35c323 100644
--- a/zerver/management/commands/export_search.py
+++ b/zerver/management/commands/export_search.py
@@ -287,9 +287,9 @@ This is most often used for legal compliance.
def transform_message(message: Message) -> dict[str, str]:
row = {
"id": str(message.id),
- "timestamp (UTC)": message.date_sent.astimezone(timezone.utc).strftime(
- "%Y-%m-%d %H:%M:%S"
- ),
+ "timestamp (UTC)": message.date_sent.astimezone(timezone.utc)
+ .replace(tzinfo=None)
+ .isoformat(" ", "seconds"),
"sender": format_sender(message.sender.full_name, message.sender.delivery_email),
"recipient": format_full_recipient(message.recipient_id, message.subject),
"content": message.content,
diff --git a/zerver/webhooks/fixtureless_integrations.py b/zerver/webhooks/fixtureless_integrations.py
index e89c44da273..2826e5dd811 100644
--- a/zerver/webhooks/fixtureless_integrations.py
+++ b/zerver/webhooks/fixtureless_integrations.py
@@ -54,7 +54,7 @@ _DT = datetime(2025, 5, 30, 2, 0, 0, tzinfo=timezone.utc)
DATETIME_GLOBAL = datetime_to_global_time(_DT)
-DATE_ISO_8601 = _DT.strftime("%Y-%m-%d")
+DATE_ISO_8601 = _DT.date().isoformat()
DATE_LONG = _DT.strftime("%A, %B %d, %Y")