org.sonar.l10n.py.rules.python.S6883.html Maven / Gradle / Ivy
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.:
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.:
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
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
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 - strftime() and strptime()
Format Codes