2

I have a string containing time stamp in format

(DD/MM/YYYY HH:MM:SS AM/PM), e.g."12/20/2014 15:25:05 pm"

. The time here is in 24 Hrs format.

I need to convert into same format but with time in 12-Hrs format.

I am using python version 2.6.

I have gone through time library of python but couldn't come up with any solution.

1

4 Answers 4

3

View Live ideOne use Python datetime,

>>> from datetime import datetime as dt
>>> date_str='12/20/2014 15:25:05 pm'

>>> date_obj = dt.strptime(date_str, '%m/%d/%Y %H:%M:%S %p')

>>> dt.strftime(date_obj, '%m/%d/%Y %I:%M:%S %p')
'12/20/2014 03:25:05 PM'
Sign up to request clarification or add additional context in comments.

1 Comment

Hello @J.F.Sebastian thank you for informing, I missed to add from datetime that why not worked, now worked correctly.
3

The trick is to convert your Input date string to Python datetime object and then convert it back to date string

import datetime

#Input Date String
t = "12/20/2014 15:25:05 pm"

#Return a datetime corresponding to date string
dateTimeObject = datetime.datetime.strptime(t, '%m/%d/%Y %H:%M:%S %p')
print dateTimeObject

Output: 2014-12-20 15:25:05

#Return a string representing the date
dateTimeString = datetime.datetime.strftime(dateTimeObject, '%m/%d/%Y %I:%M:%S %p')
print dateTimeString

Output: 12/20/2014 03:25:05 PM

Comments

1

After creating a datetime object using strptime you then call strftime and pass the desired format as a string see the docs:

In [162]:

t = "12/20/2014 15:25:05 pm"
dt.datetime.strftime(dt.datetime.strptime(t, '%m/%d/%Y %H:%M:%S %p'), '%m/%d/%Y %I:%M:%S %p')
Out[162]:
'12/20/2014 03:25:05 PM'

Comments

0

Shortest & simplest solution --

I really appreciate & admire (coz I barely manage to read man pages :P) you going through time documentation, but why use "astonishing" & "cryptic" code when simple code could get the job done

Just extract the hour part as int & replace it by hrs-12 if it is greater than 12

t = "12/20/2014 15:25:05 pm"

hrs = int( t.split()[1][:2] )

if hrs > 12:
    t = t.replace( str(hrs), str(hrs-12) )

Output

See explaination & live output here

Using Lambda

If you like one liners, checkout f() below

t = "12/20/2014 15:25:05 pm"

f = lambda tym: tym.replace(str(int(tym.split()[1][:2])), str(int(tym.split()[1][:2])-12)) if int(tym.split()[1][:2]) > 12 else tym

print(f(t))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.