-3

I have the time like 2021-05-03 14:51:56.769715. I need to convert into readable string like May 3, 2021, 2:51:56 PM in python.I need to pass the timezone also while converting it.

Is there any way we can do it in python?

Thanks in Advance :)

Barmar
  • 741,623
  • 53
  • 500
  • 612
Max
  • 1
  • 3
  • 1
    You're looking for `datetime.strftime()` – will-hedges May 03 '21 at 15:22
  • 2
    And `strptime()` to parse the original string. – Barmar May 03 '21 at 15:22
  • `datetime.fromisoformat("2021-05-03 14:51:56.769715").strftime("%B %d, %Y, %I:%M:%S %p")`? See https://strftime.org/ for more formatting / parsing directives. – FObersteiner May 03 '21 at 15:36
  • 1
    related: [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date), [How do I turn a python datetime into a string, with readable format date?](https://stackoverflow.com/questions/2158347/how-do-i-turn-a-python-datetime-into-a-string-with-readable-format-date) – FObersteiner May 03 '21 at 15:39
  • Is there any way to pass timezone with it? – Max May 03 '21 at 15:52

1 Answers1

1

This should be OK with the format you want:

from datetime import datetime

# Original string
str_date = '2021-05-03 14:51:56.769715'

# Datetime object creation from original string
obj_date = datetime.strptime(str_date, '%Y-%m-%d %H:%M:%S.%f')

# Result string with the desired format
converted_str = datetime.strftime(obj_date, '%b %-d, %Y, %-I:%-M:%-S %p')

# Print the result
print(converted_str)

The above code would print May 3, 2021, 2:51:56 PM, just as you expect. However, I have guessed that you would prefer not to have zero-padded minutes and seconds, but if you would like to you should then use %M and %S instead of %-M and %-S.

For more information about date formatting in Python you should check the Python strftime reference

Sherlock Bourne
  • 490
  • 1
  • 5
  • 10