I'm trying to update a string which should display the time differently depending on whether the current locale uses AM/PM or 24-hours
If the locale can be determined I can then update the time string using strftime("%I:%M %p")
or strftime("%H:%M")
depending on the locale
How can I programatically determine if the current locale uses AM/PM or 24-hour time?
Or is there a better way to reach the same goal (displaying a time differently depending on which locale my software is running on)?
Grateful for help and with kind regards, Tord
Using the time.strftime()
function with the %p
parameter will give the equivalent for AM/PM in the current locale, and for locales that don't use AM/PM an empty string is returned. I use this in the following way:
time_format_string = "%H:%M" # Ex: Sweden
if time.strftime("%p"): # Checking if the string contains something
time_format_string = "%I:%M %p" # Ex: US
time_of_day_string = time.strftime(time_format_string)
print(time_of_day_string)
I've tried this for two locales (one with and another without AM/PM)
Reference: https://docs.python.org/3/library/time.html#time.strftime