24 hour format for Python timestamp

Question:

Currently I’m creating timestamps with the Python time module. I created a string using this command

timestamp = time.strftime('%l:%M:%S')

However, this prints the format in a 12-hour format. Is there a way I can do this in a 24-hour format so it would show up as 20:52:53 instead of 8:52:53?

Asked By: LandonWO

||

Answers:

Try

timestamp = time.strftime('%H:%M:%S')

Check out this link for info on Python time module

https://docs.python.org/3/library/time.html#time.strftime

Answered By: mcd

If you’re located in a locale that uses the 24-hour format, you can also use '%X'.

import datetime
time = datetime.time(23, 12, 36)
timestamp = time.strftime('%X')            # '23:12:36'

dt = datetime.datetime(2023, 4, 5, 23, 12, 36)
dt.strftime('%X')                          # '23:12:36'

N.B. There’s a typo in the question. To show time in 12h format, the format should be '%I:%M:%S' (I not l). In addition, to show AM or PM, use '%I:%M:%S %p'.

For a full list of possible formats, see https://strftime.org/.

Answered By: cottontail
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.