how to change "2023-05-26" to "26 May 2023" in python with import anything or using any format
时间: 2024-02-09 17:12:22 浏览: 49
log4j-tutorial.zip_How To Change It
You can use the `strftime` function in the `datetime` module to format the date string to the desired output format. Here is the code:
```python
import datetime
date_str = "2023-05-26"
date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
new_date_str = date_obj.strftime("%d %B %Y")
print(new_date_str) # Output: 26 May 2023
```
Explanation:
1. `datetime.datetime.strptime(date_str, "%Y-%m-%d")` converts the date string to a datetime object.
2. `date_obj.strftime("%d %B %Y")` formats the datetime object to a string in the desired format ("%d" for day, "%B" for month name, "%Y" for year).
3. Finally, `print(new_date_str)` displays the new formatted date string.
阅读全文