python string转datetime函数
时间: 2023-07-08 08:09:20 浏览: 42
你可以使用Python内置的datetime模块中的strptime函数将字符串转换为datetime对象。具体实现代码如下:
```python
from datetime import datetime
date_string = "2021-09-01 12:30:45"
date_format = "%Y-%m-%d %H:%M:%S"
# 将字符串转换为datetime对象
date_object = datetime.strptime(date_string, date_format)
print(date_object)
```
在以上代码中,我们首先定义了一个字符串date_string和一个日期时间格式date_format,然后使用datetime.strptime函数将字符串转换为datetime对象,并将结果存储在date_object变量中。最后,我们使用print语句将结果打印出来。
需要注意的是,strptime函数的第一个参数是待转换的字符串,第二个参数是字符串的日期时间格式。在定义日期时间格式时,需要使用特定的占位符来表示各个部分的值,比如%Y表示年份,%m表示月份,%d表示日期,%H表示小时,%M表示分钟,%S表示秒数等等。你需要根据具体的日期时间格式来定义相应的占位符。
相关问题
python datetime.datetime string转datetime
可以使用datetime.strptime()函数将字符串转换为datetime对象,例如:
```python
import datetime
date_str = '2022-01-01 12:00:00'
date_obj = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(date_obj)
```
输出结果为:2022-01-01 12:00:00
python datetime转换成string
要将Python中的datetime对象转换成字符串,可以使用strftime函数。该函数接收一个格式字符串作为参数,返回一个字符串表示的时间。例如,如果要将datetime对象转换成"年-月-日 时:分:秒"的字符串,可以使用以下代码:
```
from datetime import datetime
dt = datetime.now() # 获取当前时间
dt_str = dt.strftime('%Y-%m-%d %H:%M:%S') # 将datetime对象转换成字符串
print(dt_str) # 输出字符串表示的时间
```
输出结果为类似"2022-01-01 12:00:00"的字符串。