We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.,Let’s look into some specific examples of strptime() function to convert string to datetime and time objects.,We can use date() function alongwith strptime() function to convert string to date object.,We can use time() function alongwith strptime() function to convert string to time object.
Python strptime() is a class method in datetime class. Its syntax is:
datetime.strptime(date_string, format)
Both the arguments are mandatory and should be string. This function is exactly opposite of strftime() function, which converts datetime object to a string. We have the similar function available in time module too, where its syntax is:
time.strptime(time_string[, format])
String to datetime
from datetime import datetime datetime_str = '09/19/18 13:55:26' datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S') print(type(datetime_object)) print(datetime_object) # printed in default format
We can use date() function alongwith strptime() function to convert string to date object.
date_str = '09-19-2018' date_object = datetime.strptime(date_str, '%m-%d-%Y').date() print(type(date_object)) print(date_object) # printed in default formatting
We can use time() function alongwith strptime() function to convert string to time object.
time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)
from datetime
import datetime
date_string = "21 June, 2018"
print("date_string =", date_string)
print("type of date_string =", type(date_string))
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)
print("type of date_object =", type(date_object))
When you run the program, the output will be:
date_string = 21 June, 2018
type of date_string = <class 'str'>
date_object = 2018-06-21 00:00:00
type of date_object = <class 'datetime.datetime'>
from datetime import datetime dt_string = "12/11/2018 09:15:32" # Considering date is in dd / mm / yyyy format dt_object1 = datetime.strptime(dt_string, "%d/%m/%Y %H:%M:%S") print("dt_object1 =", dt_object1) # Considering date is in mm / dd / yyyy format dt_object2 = datetime.strptime(dt_string, "%m/%d/%Y %H:%M:%S") print("dt_object2 =", dt_object2)
If you run this program, you will get an error.
ValueError: time data '12/11/2018'
does not match format '%d %m %Y'
Python time method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().,This return value is struct_time as returned by gmtime() or localtime().,The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().,string − This is the time in string format which would be parsed based on the given format.
Following is the syntax for strptime() method −
time.strptime(string[, format])
#!/usr/bin/python import time struct_time = time.strptime("30 Nov 00", "%d %b %y") print "returned tuple: %s " % struct_time
When we run above program, it produces following result −
returned tuple: (2000, 11, 30, 0, 0, 0, 3, 335, -1)
Python provides the strptime() method, in its datetime class, to convert a string representation of the date/time into a date object.,The code snippet below illustrates the usage of the strptime() method in Python:,The strptime() method will not work if the string argument is not consistent with the format parameter. This is shown below:,The syntax for the strptime() method is:
from datetime
import datetime
date_time_str = '18/09/19 01:55:19'
date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')
print("The type of the date is now", type(date_time_obj))
print("The date is", date_time_obj)
from datetime
import datetime
date_time_str = '180919 015519'
date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')
print("The type of the date is now", type(date_time_obj))
print("The date is", date_time_obj)
The dateutil is a third-party module. The parsing of dates in any string format is supported by the dateutil module. Internal facts about current world time zones are provided by this module. With the release of dateutil 2.0, it was recently adapted to Python 3, along with the parser functions. parse() can be used to convert a string into date-time format. The only parameter used is the string.,strptime() is available in DateTime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format. ,Another similar function is available in time module which converts a tuple or struct_time object to a string as specified by the format argument. ,Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string.
Examples:
Input: Dec 4 2018 10: 07 AM
Output: 2018 - 12 - 04 10: 07: 00
Input: Jun 12 2013 5: 30 PM
Output: 2013 - 06 - 12 17: 30: 00
Syntax of strptime function
datetime.strptime(date_string, format)
Output:
2018 - 12 - 04 10: 07: 00
Syntax of dateutil.parser.parse function
parser.parse(parserinfo = None, ** kwargs)
ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.,Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.,Return a string representing the time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.,Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see strftime() and strptime() Behavior.
object
timedelta
tzinfo
timezone
time
date
datetime
>>> from datetime import timedelta >>> delta = timedelta( ...days = 50, ...seconds = 27, ...microseconds = 10, ...milliseconds = 29000, ...minutes = 5, ...hours = 8, ...weeks = 2 ...) >>> # Only days, seconds, and microseconds remain >>> delta datetime.timedelta(days = 64, seconds = 29156, microseconds = 10)
>>> from datetime
import timedelta
>>>
d = timedelta(microseconds = -1) >>>
(d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
>>> timedelta(hours = -5) datetime.timedelta(days = -1, seconds = 68400) >>> print(_) - 1 day, 19: 00: 00
>>> from datetime
import timedelta
>>>
delta1 = timedelta(seconds = 57) >>>
delta2 = timedelta(hours = 25, seconds = 2) >>>
delta2 != delta1
True
>>>
delta2 == 5
False
>>> delta2 > delta1
True
>>> delta2 > 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'