2

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?

2
  • 1
    Did you import datetime? Also you'll want to parse the original string into an object with datetime.strptime() first, then use datetime.strftime() to get it to the format you want. Commented May 4, 2021 at 20:25
  • @chemicalwill yes, i imported datetime. how do i parse the string to a datetime object? can you help me here? Commented May 4, 2021 at 20:26

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.