如何获取格式化时间python
时间: 2023-10-10 08:06:31 浏览: 52
在 Python 中,可以使用 datetime 模块来获取格式化时间。具体操作如下:
```python
import datetime
# 获取当前时间
now = datetime.datetime.now()
# 格式化输出当前时间
print(now.strftime("%Y-%m-%d %H:%M:%S"))
```
上述代码中,`now` 变量获取了当前时间,`strftime()` 方法将时间格式化为指定格式的字符串。其中 `%Y` 表示年份,`%m` 表示月份,`%d` 表示日期,`%H` 表示小时,`%M` 表示分钟,`%S` 表示秒数。通过这些占位符可以组合出不同的时间格式。
相关问题
python 获取格式化时间字符串
以下是两种Python获取格式化时间字符串的方法:
1.使用time模块的strftime()函数
```python
import time
# 获取当前时间戳
timestamp = time.time()
# 将时间戳转换为格式化字符串
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
print(time_str) # 输出:2022-03-04 15:30:00
```
2.使用datetime模块的strftime()函数
```python
import datetime
# 获取当前时间
now = datetime.datetime.now()
# 将时间转换为格式化字符串
time_str = now.strftime("%Y-%m-%d %H:%M:%S")
print(time_str) # 输出:2022-03-04 15:30:00
```
python 格式化获取时间
可以使用 Python 内置的 datetime 模块来格式化时间,例如:
```
import datetime
now = datetime.datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)
```
该代码将输出当前时间的格式化字符串,格式为 "年-月-日 时:分:秒"。
相关推荐
![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_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)