rspec/rules/S6883/python/rule.adoc

55 lines
1.7 KiB
Plaintext
Raw Normal View History

This rule raises an issue when a date format string has the 24-hour code with the AM/PM marker or the 12-hour code without the AM/PM marker.
== Why is this an issue?
The `%p` directive in the `strftime` method is used to represent the AM/PM marker in a time string. It is commonly used in conjunction with the `%I` directive, which represents the hour in a 12-hour clock.
Using the 24-hour format directive with an AM/PM marker can lead to unwanted results e.g.:
[source,python]
----
time_string = time(16,0).strftime("%H:%M %p")
print(time_string)
----
will print `16:00 PM` which makes no sense.
On the other hand the AM/PM marker is needed when the 12-hour format directive is used to show complete information about an hour e.g.:
[source,python]
----
time_string = time(16,0).strftime("%I:%M")
print(time_string)
----
will print 04:00 without indicating if the time is in the morning or the afternoon.
== How to fix it
Use either the 12-hour time format with an AM/PM marker or the 24-hour format without.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
from datetime import time
def foo():
t = time(16, 0)
formatted_time1 = t.strftime("%H:%M %p") # Noncompliant: 16:00 PM
formatted_time2 = t.strftime("%I:%M") # Noncompliant: 04:00
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
from datetime import time
def foo():
t = time(16, 0)
formatted_time1 = t.strftime("%I:%M %p") # OK: 04:00 PM
formatted_time2 = t.strftime("%H:%M") # OK: 16:00
----
== Resources
=== Documentation
* Python documentation - https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes[strftime() and strptime() Format Codes]