In this tutorial, we’ll see a way to convert string to DateTime in python.
When we fetch the worth from a textbox whereas operating with GUI in python, by default the worth has string datatype.
So here are some ways in which to convert a string into DateTime.
Python Convert String to Datetime
1.exploitation datetime library
code
from datetime import datetime
date_string = '06-02-2018'
date_object = datetime.strptime(date_string, '%d-%m-%Y')
print(date_object)
output
2018-02-06 00:00:00
Where 00:00:00 represents time. In above program, directives
%d = day in 2 digit format
%m = month in 2 digit format
%Y = year in 4 digit format
Lets say our string is ’06-02-2018′
On different hand if our string is like this ‘Sep thirteen 2012 11:00PM’ then we will convert it exploitation this manner.
code
from datetime import datetime
date_string = 'Feb 02 2012 08:00PM'
date_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p')
print(date_object)
output
2012-02-02 20:00:00
where directives
%b = short form of month name
%I = hour in short format (0-12)
%M = Minutes in 2 digit format (0-60)
%p = AM or PM
the exploitation of external library dateutil – a computer programme
To use this library 1st we’ve to put in it. to put in it, open Terminal or electronic communication and kind
‘pip install python-dateutil’
And press enter key. currently we will use this library.
2.By Using external library time string
Again to use this library we’ve to put in it. to put in it open your terminal or electronic communication and kind
‘pip install timestring’
After the installation is finished, currently we will use this library in our program.
import timestring
date_string = 'feb 06 2018 08:00PM'
date_object = timestring.Date(date_string)
print(date_object)
Output:
2018-02-06 20:00:00
3.Using of external library date parser
To install data parser, open terminal or electronic communication and enter the following command.
‘pip install dateparser’
Now we will use it.
import dateparser
date_string = '02/06/2018'
date_object = dateparser.parse(date_string)
print(date_object)
Output
2018-02-06 00:00:00
And if our date string is ‘Fri, 06 February 2018 08:55:00’ then the program is going to be same as higher than, simply replace the date_string.
You can raise your queries associated with python convert string to DateTime.