python 时间转字符串
时间: 2023-09-30 08:01:39 浏览: 36
要将 Python 中的时间转换为字符串,可以使用 `strftime()` 函数。下面是一个简单的示例:
```python
import datetime
now = datetime.datetime.now()
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
print(now_str)
```
输出将会是当前时间的字符串表示,格式为 `年-月-日 时:分:秒`。你还可以根据需要自定义日期时间格式,具体的格式代码可以参考 Python 的官方文档:[strftime() 和 strptime() 格式化指南](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)。
相关问题
python时间转换字符串
要将时间转换为字符串,可以使用strftime()函数。以下是一个示例:
```python
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
```
输出:
```
2022-01-01 12:00:00
```
在上面的代码中,我们使用datetime模块获取当前时间,并使用strftime()函数将其转换为字符串。strftime()函数接受一个参数,该参数是格式化字符串,指示要包含哪些时间信息。在这个例子中,我们使用了"%Y-%m-%d %H:%M:%S"格式,它表示年份、月份、日期、小时、分钟和秒。
python 当前时间转字符串
可以使用 Python 的 datetime 模块来实现将当前时间转换为字符串的功能。以下是一个示例代码:
```python
import datetime
now = datetime.datetime.now()
date_string = now.strftime("%Y-%m-%d %H:%M:%S")
print(date_string)
```
这段代码会输出当前时间的字符串表示,格式为 "年-月-日 时:分:秒"。你可以根据需要调整 strftime 函数中的格式字符串来改变输出的格式。