1

I have a pandas column with a date and time as value - 20131019T150000. I would like to convert these to something like 3pm, 19th October 2013.

Example -

ID   DATE         
1    20131019T150000    
2    20180202T100000    

output should be something like:

ID   DATE         
1    3pm, 19th October 2013   
2    10am, 2nd February 2018   

Thanks in advance.

Equinox
  • 6,483
  • 3
  • 23
  • 32
DarkKnight
  • 57
  • 5

3 Answers3

1

First you'll need to convert the string to a Python datetime.datetime object to easily work with it. To do that you can use classmethod datetime.strptime(date_string, format) (see in docs), which returns a datetime corresponding to date_string, parsed according to format.

Then, to print the datetime object as any string you'd want, there is this other method datetime.strftime(format) (see in docs) which return a string representing the date and time, controlled by an explicit format string.

(Note: For more about the formating directives, follow this link to docs)

So for the given string you could proceed as follow:

from datetime import datetime


def get_suffix(day: int) -> str:
    # https://stackoverflow.com/a/739266/7771926
    if 4 <= day <= 20 or 24 <= day <= 30:
        suffix = "th"
    else:
        suffix = ["st", "nd", "rd"][day % 10 - 1]
    return suffix


def process_date(date: str) -> str:
    dt_obj =  datetime.strptime(date, '%Y%m%dT%H%M%S')
    return dt_obj.strftime('%I%p, %d{} %B %Y').format(get_suffix(dt_obj.day))


def main(): 
    date_str = '20131019T150000'
    print(process_date(date_str))


if __name__ == '__main__':
    main()

If you execute the script, this is what is printed to console: 03PM, 19th October 2013

Glad if helps.

Nestor
  • 519
  • 1
  • 7
  • 21
0

You could use the datetime module of python (in-built). Here's a function to which does what you want:

import datetime
def func(input_st):
    dt_obj = datetime.datetime.strptime(input_st, '%Y%m%dT%H%M%S')
    return dt_obj.strftime('%I%p, %d %B %Y')

Hope this solves it! You could (maybe) use this function for every item.... maybe using the 'map' inbuilt function of python.

cyberGhoul
  • 99
  • 2
  • 7
0
from datetime import datetime
s="20131019T150000"
dt_obj1=datetime.strptime(s,'%Y%m%dT%H%M%S')
print(dt_obj1.strftime("%I %p,%d %B %Y"))

Output:
03 PM,19 October 2013
sourab maity
  • 1,025
  • 2
  • 8
  • 16