Python具有广泛的日期和时间操作功能。在本文中,我们将了解如何将格式正确的字符串转换为日期时间,反之亦然。
datetime模块的strptime函数可以通过采用适当的格式说明符将字符串转换为datetime。
import datetime dt_str = 'September 19 2019 21:02:23 PM' #Given date time print("Given date time: \n",dt_str) #Type check print("Data Type: ",type(dt_str)) #Format dtformat = '%B %d %Y %H:%M:%S %p' datetime_val = datetime.datetime.strptime(dt_str, dtformat) print("After converting to date time: \n",datetime_val) #Type check print("Data type: ",type(datetime_val)) # Reverting to string dtstr_new=str(datetime_val) print("The string Date time ",dtstr_new) print("Data type: ",type(dtstr_new))
输出结果
运行上面的代码给我们以下结果-
Given date time: September 19 2019 21:02:23 PM Data Type: After converting to date time: 2019-09-19 21:02:23 Data type: The string Date time 2019-09-19 21:02:23 Data type:
str函数会将其参数转换为字符串。因此,在这里,我们使用Today函数获取日期时间值,并将其作为参数提供给str函数。
import datetime print("Date time data type: \n",datetime.datetime.today()) print("Data type: \n",type(datetime.datetime.today())) dtstr= str(datetime.datetime.today()) print("String Date time:\n ",dtstr) print("Data type: \n",type(dtstr))
输出结果
运行上面的代码给我们以下结果-
Date time data type: 2020-05-18 11:09:40.986027 Data type: String Date time: 2020-05-18 11:09:40.986027 Data type: