Date time format conversion in python

18,571

Solution 1

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'

Solution 2

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

Solution 3

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'
Share:
18,571
ankit
Author by

ankit

I like programming

Updated on June 05, 2022

Comments

  • ankit
    ankit almost 2 years

    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.

  • Jaykumar Patel
    Jaykumar Patel about 9 years
    Hello @J.F.Sebastian thank you for informing, I missed to add from datetime that why not worked, now worked correctly.