利用datetime库输出5种不同的日期格式
时间: 2024-06-06 09:10:18 浏览: 25
Sure, I can do that! Here are five different date formats that can be outputted using the datetime library:
1. yyyy-mm-dd
Code: `datetime.today().strftime('%Y-%m-%d')`
Output: 2022-01-01
2. mm/dd/yyyy
Code: `datetime.today().strftime('%m/%d/%Y')`
Output: 01/01/2022
3. dd-mm-yyyy
Code: `datetime.today().strftime('%d-%m-%Y')`
Output: 01-01-2022
4. yyyy年mm月dd日
Code: `datetime.today().strftime('%Y年%m月%d日')`
Output: 2022年01月01日
5. Day, Month dd, yyyy
Code: `datetime.today().strftime('%A, %B %d, %Y')`
Output: Saturday, January 01, 2022
相关问题
请利用datetime库输出5种不同的日期格式
1. YYYY-MM-DD: 2022-02-27
2. DD/MM/YYYY: 27/02/2022
3. MMM DD, YYYY: Feb 27, 2022
4. DD MMM, YYYY: 27 Feb, 2022
5. YYYY/MM/DD: 2022/02/27
可以通过以下Python代码实现:
```python
import datetime
# 获取当前日期
today = datetime.date.today()
# 输出不同的日期格式
print("YYYY-MM-DD:", today.strftime("%Y-%m-%d"))
print("DD/MM/YYYY:", today.strftime("%d/%m/%Y"))
print("MMM DD, YYYY:", today.strftime("%b %d, %Y"))
print("DD MMM, YYYY:", today.strftime("%d %b, %Y"))
print("YYYY/MM/DD:", today.strftime("%Y/%m/%d"))
```
利用datetime库输出5种不同的日期格式应该怎么做
可以使用 datetime 库中的 strftime() 函数输出不同的日期格式。下面是5种不同的日期格式和对应的 strftime() 格式代码:
1. 2021-07-01 : `%Y-%m-%d`
2. 07/01/21 : `%m/%d/%y`
3. Thursday, July 1st 2021 : `%A, %B %dth %Y`
4. 2021-07-01 12:34:56 : `%Y-%m-%d %H:%M:%S`
5. 2021年7月1日 : `%Y年%m月%d日`
下面是一个示例代码,演示如何使用 datetime 库输出上述 5 种不同的日期格式:
```python
from datetime import datetime
# 获取当前日期时间
now = datetime.now()
# 输出不同的日期格式
print(now.strftime("%Y-%m-%d"))
print(now.strftime("%m/%d/%y"))
print(now.strftime("%A, %B %dth %Y"))
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%Y年%m月%d日"))
```
输出结果如下:
```
2021-07-01
07/01/21
Thursday, July 01th 2021
2021-07-01 12:34:56
2021年07月01日
```
注意,strftime() 函数中的格式代码区分大小写。例如,`%Y` 表示年份的四位数字,而 `%y` 则表示年份的两位数字。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)