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.

EdChum
  • 376,765
  • 198
  • 813
  • 562
ankit
  • 1,499
  • 5
  • 29
  • 46
  • related: [Convert 24 hours time to 12 hours in python](http://stackoverflow.com/q/13855111/4279) – jfs Mar 03 '15 at 19:34

4 Answers4

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'
user229044
  • 232,980
  • 40
  • 330
  • 338
Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
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

planet260
  • 1,384
  • 1
  • 14
  • 30
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'
EdChum
  • 376,765
  • 198
  • 813
  • 562
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))
RinkyPinku
  • 410
  • 3
  • 20