0

how can I convert 24 hour format to 12 hour format while using now() function.

from datetime import *

current_time = datetime.now()

print(current_time)

Any other ways to do this than strftime().

codework
  • 25
  • 1
  • 9
  • 6
    Does this answer your question? [How can I convert 24 hour time to 12 hour time?](https://stackoverflow.com/questions/13855111/how-can-i-convert-24-hour-time-to-12-hour-time) – Jacob Celestine May 01 '21 at 13:38
  • is there any other way of doing it than strftime(). – codework May 01 '21 at 13:42
  • You can check this [question](https://stackoverflow.com/questions/13554589/24-hour-time-conversion-to-12-hour-clock-problemsetquestion-on-python) whose answer proposes an implementation of what you want to do. – Ewran May 01 '21 at 13:45
  • "is there any other way of doing it than strftime()"—we can't help you find a good solution if you reject good answers without explaining why. – ChrisGPT was on strike May 01 '21 at 15:15
  • 1
    Note that `current_time` is a [datetime object](https://docs.python.org/3/library/datetime.html#datetime-objects), not a string. datetime objects do not have a *format* like 12h or 24h clock. Only a string that represents date & time has that - so you *have* to use `strftime` if you want to have the one or the other format. – FObersteiner May 01 '21 at 16:42
  • 1
    Please also note [Why is “import *” bad?](https://stackoverflow.com/q/2386714/10197418) – FObersteiner May 01 '21 at 16:43

1 Answers1

0

you can use strftime function

from datetime import *
current_time = datetime.now().strftime("%I:%M %p")
print(current_time)
Muhammad Safwan
  • 869
  • 7
  • 12
  • 1
    See the question I linked in the comments section - please avoid suggesting `from ... import *` (although that appears in the OP's example). Here you just need `from datetime import datetime`. – FObersteiner May 01 '21 at 16:47