how to change "2023-05-26" to "26 May 2023" in python
时间: 2023-07-05 09:10:26 浏览: 68
You can use the datetime module in Python to achieve this. Here's an example code snippet:
```python
from datetime import datetime
date_str = "2023-05-26"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d %B %Y")
print(formatted_date)
```
This code first converts the date string "2023-05-26" into a datetime object using the `strptime` method. Then it formats the datetime object into a new string with the desired format "26 May 2023" using the `strftime` method. Finally, it prints the formatted string.
相关问题
how to change "2023-05-26" to "26 May 2023" in python with import anything
To achieve this, you can use the `dateutil` package which can be installed via pip. Here is the code:
```python
from dateutil import parser
date_str = "2023-05-26"
date_obj = parser.parse(date_str)
new_date_str = date_obj.strftime("%d %B %Y")
print(new_date_str) # Output: 26 May 2023
```
Explanation:
1. `parser.parse(date_str)` 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.
how to change "2023-05-26" to "26 May 2023" in python with import anything or using any format
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.