0
from datetime import datetime
import time
timestamp = 1595059353398/1000
dt_object = datetime.fromtimestamp(timestamp)
date_time = dt_object.strftime("%m/%d/%Y, %H:%M:%S")

print(date_time)

I got the output was 07/18/2020, 13:32:33 but I need Output Should be : 7/18/2020, 1:32:33 PM in this format

mahendra
  • 37
  • 5
  • 3
    Does this answer your question? [Converting python string to datetime obj with AM/PM](https://stackoverflow.com/questions/31955761/converting-python-string-to-datetime-obj-with-am-pm) – mpx Jul 24 '20 at 09:27

1 Answers1

1

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).

JPI93
  • 1,507
  • 5
  • 10