In Python, the data type which represents the date is called datetime
class. Apart from the datetime
class, the date can also be represented as a string
which we can see in the code below:
myDate = "16-July-2023"#Prints the Date as a stringprint(myDate)
Python allows you to convert the string
type date into a datetime
object using strptime()
method.
The syntax for the method used to convert string to datetime
object is strptime(x,y)
where:
x
is the the date entered in the string
.
y
is the format directives in which the string
date is stored. Following are the directives for date.
Tags | Definition | Example |
%d | Date of the month (zero padded) | 01,02,03,...,31 |
%-d | Date of the month (without zero padding) | 1,2,3,...,31 |
%B | Full month name | January, February,..., December |
%b | Abbreviated month | Jan, Feb, Mar,..., Dec |
%m | Month number (zero-padded) | 01, 02, 03,..., 12 |
%-m | Month number (without zero padding) | 1, 2, 3,..., 12 |
%y | Year without century (zero-padded) | 00, 01, 02,..., 99 |
%-y | Year without century (without zero padding) | 0, 1, 2,.., 99 |
%Y | Year with century | 1900, 2001, 2023 etc. |
The code below demonstrates the conversion of the string
into a datetime
object using strptime()
method:
from datetime import datetime#Date as a stringdateString = "02-July-2023"print(f"Date as {type(dateString)} is {dateString}")#Converting string date into datetime objectdateTimeObj = datetime.strptime(dateString, "%d-%B-%Y")print(f"Date as {type(dateTimeObj)} is {dateTimeObj}")
Line 1: Imports datetime
class from datetime
library.
Line 3–5: Stores the date as a string
in dateString
variable and displays it along with its type.
Line 7–9: Uses strptime()
method for converting the date (stored in dateString
variable) in a datetime
object. The converted date is then stored in the dateTimeObj
variable. The following figure explains the use of appropriate directives in the code:
The code will only be executed if the entered directives adhere to the format in which the string is stored. Otherwise, the code will show an error, as illustrated below:
from datetime import datetime#Date as a stringdateString = "02-July-2023"print(f"Date as {type(dateString)} is {dateString}")#Converting string date into datetime objectdateTimeObj = datetime.strptime(dateString, "%d-%b-%Y")print(f"Date as {type(dateTimeObj)} is {dateTimeObj}")
%b
directive was used in the code above, although the month name is not abbreviated. Hence it threw an error.
What is the correct use of strptime()
in the following scenario?
from datetime import datetimedef myDate():#Date as a stringdateString = "04/Dec/23"dateTimeObj = #write your solution herereturn dateTimeObj
Free Resources