Python has extensive date and time manipulation capabilities.In this article we'll see in how is string with proper format can we converted to a datetime and the vice versa.
With strptime
This strptime function from datetime module can do the conversion from string to datetime by taking appropriate format specifiers.
Example
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))
Output
Running the above code gives us the following result −
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:
With str
The str function will convert its parameter to a string. So here we take a datetime value by using the today function and supply it as a parameter to the str function.
Example
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))
Output
Running the above code gives us the following result −
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: