Python时间类型和字符串转换
时间: 2023-03-30 19:03:59 浏览: 105
Python中可以使用datetime模块来处理时间类型,可以使用strftime()方法将时间类型转换为字符串,也可以使用strptime()方法将字符串转换为时间类型。例如:
将时间类型转换为字符串:
```python
import datetime
now = datetime.datetime.now()
str_time = now.strftime('%Y-%m-%d %H:%M:%S')
print(str_time)
```
将字符串转换为时间类型:
```python
import datetime
str_time = '2022-01-01 00:00:00'
time = datetime.datetime.strptime(str_time, '%Y-%m-%d %H:%M:%S')
print(time)
```
相关问题
python 中如何把字符串转换成datatime
在 Python 中,可以使用 `datetime` 模块中的 `datetime.strptime()` 函数将字符串转换成 `datetime` 类型,代码示例如下:
```python
from datetime import datetime
date_string = "2021-08-25 10:30:00"
date_format = "%Y-%m-%d %H:%M:%S"
datetime_obj = datetime.strptime(date_string, date_format)
print(datetime_obj)
```
输出:
```
2021-08-25 10:30:00
```
在上面的代码中,`date_string` 是要转换的字符串,`date_format` 是字符串的格式,`datetime_obj` 是转换后的 `datetime` 对象。`%Y` 表示年份,`%m` 表示月份,`%d` 表示日期,`%H` 表示小时,`%M` 表示分钟,`%S` 表示秒。你可以根据实际情况修改 `date_string` 和 `date_format` 的值。
Python将字符串转换为日期时间
可以使用datetime模块中的strptime()函数来将字符串格式的日期时间转换为datetime类型的日期时间。例如:
```
from datetime import datetime
date_string = '2021-08-03 08:30:00'
date_time = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
print(date_time)
```
这段代码将字符串'2021-08-03 08:30:00'转换为datetime类型的日期时间,输出结果为:2021-08-03 08:30:00。