1

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

Magicofcolors
  • 11
  • 1
  • 2
  • 3
  • 1
    Possible duplicate of [How can I convert 24 hour time to 12 hour time?](https://stackoverflow.com/questions/13855111/how-can-i-convert-24-hour-time-to-12-hour-time) – voiDnyx Oct 26 '17 at 22:36
  • @voiDnyx That isn't a dupe of this. – roganjosh Oct 26 '17 at 22:37

3 Answers3

4

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
williamlopes
  • 406
  • 6
  • 16
  • This almost worked! I need am/pm in a lower case whereas your solution returns it in upper case. your code returns '28 Oct 2017 05:22 PM' whereas I need the formatted date as '28 Oct 2017 05:22 pm' – Magicofcolors Oct 28 '17 at 04:07
1

In Robot Framework there is a standard library DateTime that can be used here. The keyword Convert Date can be used to convert a standard date-time string into another format. The formatting format used by the python command strftime() Documentation applies here as well.

In the below robot code the formatting is performed:

*** Settings ***
Library    DateTime    

*** Test Cases ***
TC
    ${date}    Convert Date    2017-10-25 15:24:38    result_format=%d %b %Y %I:%M %p

Which results in the following output:

${date} = 25 Oct 2017 03:24 PM
A. Kootstra
  • 6,827
  • 3
  • 20
  • 43
  • I added the DateTime Library but when I use 'Convert Date ' i get a red line under Convert Date saying key definition not found. I am using Pycharm ide. What could it be? I am using a bunch of other libraries and they are working fine. – Magicofcolors Oct 29 '17 at 06:35
  • 1
    Keep in mind that PyCharm and all other IDE's are only an IDE to generate .robot files and do not play a role in the actual execution of the script. If you run this the above example it will work in robot framework it will work, regardless of the IDE complaining it can't find the keyword. That is a separate issue and unrelated to this as the DateTime library is part of the robot framework installation. – A. Kootstra Oct 29 '17 at 07:01
0

How to Parse & Convert time formats in python:

>>> datetime(*strptime(s, "%Y-%m-%dT%H:%M:%S+0000")[0:6]).strftime("%B %d, %Y %I:%M %p")

'July 16, 2013 04:14 PM'

read more about parsing & converting process: https://docs.python.org/2/library/datetime.html

Ori a
  • 314
  • 1
  • 8