How to convert date time format from '2017-10-25 15:24:38' to '25 Oct 2017 03:24 pm' in Python

Magicofcolors picture Magicofcolors · Oct 27, 2017 · Viewed 13k times · Source

Is there any python library that would let me convert date time format from '2017-10-25 15:24:38' to '25 Oct 2017 03:24 pm'

in node.js there is a library called moments.js that does it. is there a way to do it in Python?

P.S. I'm using robot framework

Answer

williamlopes picture williamlopes · Oct 27, 2017

You could use:

from datetime import datetime
datetime_object = datetime.strptime('2017-10-25 15:24:38', '%Y-%m-%d %H:%M:%S')
datetime_string = datetime_object.strftime('%d %b %Y %I:%M %p')

EDIT: If you desire AM/PM in lowercase:

dt_s = datetime_object.strftime('%d %b %Y %I:%M')
dt_s_ampm = datetime_object.strftime('%p').lower()
final_dt = dt_s + ' ' + dt_s_ampm