Search code examples
pythondatetimestrftime

Datetime object to string containing AM/PM


I currently have a datetime object with time that looks like 06:00:00 and am trying to convert it to a string that looks like "6:00 am".

I have been trying to use the Python Strftime libraries but am having trouble, could someone point me in the right direction? Thanks :)


Solution

  • You should just be able to use %I:%M %p, as per the following transcript:

    >>> import datetime
    
    >>> now = datetime.datetime.now()
    
    >>> now
    datetime.datetime(2020, 3, 30, 14, 6, 49, 62354)
    
    >>> print(now.strftime("%I:%M %p"))
    02:06 PM
    

    See here for a list of the different format codes.

    If, as your question implies, you need it without a leading zero on the hour, and in lower-case, you can just use regular expressions for the former and lower() for the latter:

    >>> import re
    
    >>> print(re.sub("^0", "", now.strftime("%I:%M %p")).lower())
    2:06 pm