Please see solution and explanatory/advisory notes below.
Solution
from datetime import datetime
import re
format = '%m/%d/%Y %I:%M %p'
timestamp = 1595059353398/1000
dt_object = datetime.fromtimestamp(timestamp)
date_time = dt_object.strftime(format)
date_time = re.sub('(^0)|((?<=\/)0)|(?<=\s)0', '', date_time)
print(date_time)
Format
In format
, %I
specifies 12-hour clock and %p
specifies the locale’s equivalent of either AM or PM - see datetime
docs.
re
to strip leading zeroes
The solution makes use of the builtin re
module to replace any leading zeroes that may be present at the start ((^0)
), following any instance of '/'
within the string (((?<=\/)0)
), or following a space ((?<=\s)0
) - as per the desired output described in your question.
I would consider thinking about your requirements some more and evaluating whether or not you actually need to remove leading zeroes - as per the desired output described in original post - working with a fixed length (i.e. allowing leading zeroes) certainly has it's advantages in many use cases.
If you do decide that you no longer want to remove leading zeroes in the string produced you can simply omit the line date_time = re.sub(*args)
.