时间格式化python
时间: 2023-08-03 17:08:15 浏览: 40
要将时间格式化为特定的字符串格式,可以使用Python中的datetime模块和strftime()函数。下面是一个示例:
```python
from datetime import datetime
# 获取当前时间
now = datetime.now()
# 将时间格式化为字符串
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)
```
这将输出当前时间的字符串表示,格式为"年-月-日 时:分:秒"。你可以根据需要修改strftime()函数中的格式字符串来获得不同的时间格式。更多关于格式字符串的信息可以参考Python官方文档中的strftime()函数说明。
相关问题
日期格式化输出Python
在Python中,可以使用datetime模块来进行日期格式化输出。下面是一个简单的示例:
```python
import datetime
# 获取当前日期和时间
now = datetime.datetime.now()
# 格式化输出日期
formatted_date = now.strftime("%Y-%m-%d")
print("Formatted date:", formatted_date)
# 格式化输出时间
formatted_time = now.strftime("%H:%M:%S")
print("Formatted time:", formatted_time)
# 格式化输出日期和时间
formatted_datetime = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted datetime:", formatted_datetime)
```
上述代码中,我们首先导入了datetime模块。然后使用`datetime.datetime.now()`获取当前日期和时间。接着,使用`strftime()`方法对日期和时间进行格式化输出。
在`strftime()`方法中,我们可以使用不同的格式化字符串来定义输出的格式。例如,`%Y`表示四位数的年份,`%m`表示两位数的月份,`%d`表示两位数的日期,`%H`表示24小时制的小时数,`%M`表示分钟数,`%S`表示秒数。
输出结果如下:
```
Formatted date: 2022-01-01
Formatted time: 12:34:56
Formatted datetime: 2022-01-01 12:34:56
```
python格式化输出日期时间
以下是两种Python格式化输出日期时间的方法:
1. 使用time模块输出格式化日期时间字符串:
```python
import time
date_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(date_str) # 输出:2022-08-18 16:30:00
```
2. 使用格式化字符串占位符输出带汉字的日期时间:
```python
import time
print(time.strftime('%Y{}%m{}%d{} %H{}%M{}%S{}', time.localtime()).format("年","月","日","时","分","秒")) # 输出:2022年08月18日 16时30分00秒
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)