Search code examples
python-3.xdatetimepython-datetimestrftime

Convert date string to another date string format


I am trying to convert a string datetime to another string time i.e... May 4, 2021 but I am getting the following error

#convert '2021-05-04T05:55:43.013-0500' ->>> May 4, 2021

timing = '2021-05-04T05:55:43.013-0500'
ans = timing.strftime(f'%Y-%m-%d 'f'%H:%M:%S.%f')

Here is the error

AttributeError: 'str' object has no attribute 'strftime'

What am I doing wrong?


Solution

  • You want datetime.strptime() not timing.strftime(). timing is a string that doesn't have any functions called strftime. The datetime class of the datetime moduleI know, it's confusing, OTOH, does have a function to parse a string into a datetime object. Then, that datetime object has a function strftime() that will format it into a string!

    from datetime import datetime
    
    timing = '2021-05-04T05:55:43.013-0500'
    
    dtm_obj = datetime.strptime(timing, f'%Y-%m-%dT%H:%M:%S.%f%z')
    
    formatted_string = dtm_obj.strftime('%b %d, %Y')
    print(formatted_string)
    # Outputs:
    # May 04, 2021