How to convert a string to a date in Python

In this tutorial, there will be a demonstration of how to print object attributes in Python using prevalent examples. As you may know, python is friendly for date and time data manipulation. You can get your hands on the same data in many ways. However, this article will look at how to convert a string into a date object in Python. Python programming language represents a time, date, and time of day. Date values can be parsed and converted into other date formats.  

*Working on Jupyter Notebook Anaconda Environment, Python version 3+. 

Why do we need a date class in Python?

The date helps us build software that uses time, date, and other related functions. However, Python’s date module provides date and time manipulation functions. However, Python is a programming language that can build real-time applications, websites, and software systems. That’s why the python code must execute the date/time in the correct format. 

Moreover, Dates are very important in programming and Python when dealing with real-time projects. For example, if you write a program for an inventory store that calculates the price of an item, you need to make sure the date picker can set the correct date for the program. Therefore, that’s where a date class comes in handy.

What is the placeholder for date format in Python?

The date format in Python is a string that specifies how dates should format. The placeholder to represent date format in Python is:

%Y is a placeholder to represent the year

%y to represent the last two decimals of the year

%m is a placeholder to represent the month

%B to print the full month and;

%b represents to print the first three characters of the particular month

%d is a specifier to represent the day

%H to represent the hour

%M is a placeholder to represent the minute

%S to represent second

What is the function for date format in Python?

In Python, three functions can be used to format dates: strftime, datetime.date and datetime.datetime. Each function has a set of parameters you can use to customize its output.

Difference between strptime and strftime function

However, strptime it converts a string to a datetime object, while strftime converts a datetime object to other formats. 

Python allows you to change the date format using one of five functions: strftime, datetime.date, and datetime.time, datetime.delta and datetime.datetime. However, commonly used strftime, datetime.date accepts a string as input and returns an object. 

In Python, the strftime() function for date format is follows as:

date.strftime(format, time_string)

This function takes two arguments:

format – which is a string representing the format you want to print your date in (for example, %Y-%m-%d)

time_string – this is the string that represents the time at which you want to print your date (for example, “2023-04-31“).

Steps to print a string to date in Python

  • datetime: A built-in module in Python that enables us to deal with dates and times.
  • strptime: the method of the datetime module from the python standard library that converts a string representing a date and time according to a specified format.
  • Input string: A string that we want to convert to a date/time object.
  • “%m/%d/%Y – %H:%M:%S”: It tells strptime to interpret and match the format with the input string. However, it indicates that the input string should have the same date and time format. Otherwise, it returns the error time data does not match format '%m/%d/%Y  %H:%M:%S'”

Methods to convert a string to a date in Python

Using datetime.strptime() to convert a string to a date in Python

Date and time values can be parsed and converted into other date formats using Python’s built-in datetime module. The Datetime module takes the strptime() function as an attribute. The strptime() function takes two arguments, as discussed above.

  • The formatted date-time string
  • And a particular format should match the date time format declared within a string. 
  • For sure, you have to import the datetime module to work with the date and time.
  • The string string='1/18/2023 - 11:37:39' represents the date and time in the format of %m/%d/%Y - %H:%M:%S. Where %m represents the month, %d Represents the day of the month, %Y represents the year, %H represents the hour in two-digit format, %M represents the minutes, and %S represents the seconds.
  • The datetime.strptime() a function is used to convert the string into a datetime object.
  • The exactly same %m/%d/%Y - %H:%M:%S the parameter passed to the strptime() function that matches the format of the input string, 
  • Finally, the print() function prints the date and time in its default format along with its data type.
#import datetime
from datetime import datetime
#syntax to print date or time in a particular format
string='1/18/2023 - 11:37:39'
#import datetime.strptime() module to set a specific date and time
date_time = datetime.strptime(string, "%m/%d/%Y - %H:%M:%S")
print('date:' , date_time)
#executes string date and converts it's type to object
print ("The converted string: ", date_time, type(date_time))
date: 2023-01-18 11:37:39
The converted string:  2023-01-18 11:37:39 <class 'datetime.datetime'>

The above example code uses the datetime module from Python’s library to convert a string representation of a date and time to a Python datetime object.

The datetime.strptime() the function is used to convert and parse the string into a datetime object. However, the datetime.strptime() function takes two arguments, the first argument is to read and convert the string, and the second argument matches the date and time format with the provided input string. Hence, the resulting datetime object is then printed in its default format using the print() function and its datetime.datetime type, which is a class object.

Print date only in Python

You can use the same code above to print the date. You just specify the date in the required input string. Overall, the below code only converts and parses the date object that represents only the date and returns output. 

For this particular task, the datetime module in Python converts a string in the format of "%m/%d/%Y - %H:%M:%S” into a date object.

  • .date() function retrieves only the date portion of the datetime object returned by strptime and returns it as a separate date object.
#import datetime
from datetime import datetime
#syntax to print date or time in a particular format
string='1/18/2023 - 11:37:39'
#import datetime.strptime() module to set specific date and time
date_time = datetime.strptime(string, "%m/%d/%Y - %H:%M:%S").date()
print('date:' , date_time)
#executes string date and convert it's type to object
print ("The converted string: ", date_time, type(date_time))
date: 2023-01-18
The converted string:  2023-01-18 <class 'datetime.date'>

Here’s is the simplest way to retrieve date from date time string format

#import dateutil Python standard library from parser module
from dateutil import parser
#import datetime module
import datetime
#string to be converted
input_string = 'August 14 2023 12:31:00 AM'
# the parser module to parse a string date
parser.parse(input_string).date()
datetime.date(2023, 8, 14)

How to retrieve time from the strptime() function?

The procedure will be the same as for retrieving the date only, demonstrated above. For this particular task, the datetime module in Python converts a string in the format of “%m/%d/%Y - %H:%M:%S” into a time object.

  • .time() function retrieves only the time portion of the datetime object returned by strptime, and returns it as a separate time object.
#import datetime
from datetime import datetime
#syntax to print date or time in a particular format
string='1/18/2023 - 11:37:39'
#import datetime.strptime() module to set specific date and time
date_time = datetime.strptime(string, "%m/%d/%Y - %H:%M:%S").time()
print('date:' , date_time)
#executes string date and convert it's type to object
print ("The converted string: ", date_time, type(date_time))
date: 11:37:39
The converted string:  11:37:39 <class 'datetime.time'>

Using the Alignment operator ‘=’ with f-string to convert string to date

The “=” is the sign of alignment. And using = alignment operator is used to format the date or time we want to print. Here it prints the variable ‘today’ within the output string. 

The command line {today=}: demonstrates that the variable within the curly braces will be replaced with the current variable’s value. The = sign after the variable name depicts to include the variable name in the output string, along with its value. However, the %b will display the character for the month instead of taking a by-default numeric value.

from datetime import datetime
today = datetime.today().strftime("%b %d,%Y - %H:%M:%S")
# '=' alignment operator
f'date and time: {today=}'
"date and time: today='Mar 29,2023 - 14:23:01'"

dateutil module to convert string to a date in Python

Using the dateutil module to parse date and time in Python. Here is how it executes:

  • To convert a string to a date, first import the parser module from the dateutil Python standard library to parse and work with dates and times in Python.
  • Then, the parser.parse() function is used to read a string formatted in a specific date and time (“August 14 2023 12:31AM“) and convert it to a datetime object.
  • The parsed datetime object in the above command line is stored in the date_time variable.
  • As a final step, print() displays the string date and time and its data type and converts it into a numeric format by default.
#import dateutil Python standard library from parser module
from dateutil import parser
#import parser.parse() module to set specific dates and time
date_time = parser.parse("August 14 2023 12:31AM")
print('date:' , date_time)
#executes string date and converts its type to object
print ("The converted string: ", date_time, type(date_time))
date: 2023-08-14 00:31:00
The converted string:  2023-08-14 00:31:00 <class 'datetime.datetime'>

Overall, the parser.parse() module interprets the string date and time “August 14 2023 12:31AM" and convert to a datetime object and parses it to numeric form, and the data time type of the date_time object is datetime.datetime.

Using list comprehension in aggregation with dateutil and parser module

Here is how to list comprehension plays a role to convert a string to a date in Python. Here is how the process executes.

#import dateutil Python standard library from parser module
import dateutil
#declare an empty variable to store output value
date_time = []
#using append function to add output to list
date_time.append('August 14 2023 12:31AM')
#list comprehension using in aggregation with parser module
a=[parser.parse(x) for x in date_time]
print(a, type(a))
[datetime.datetime(2023, 8, 14, 0, 31)] <class 'list'>

Above code imports the dateutil Python standard library and uses the parser module to parse a string date and time “August 14 2023 12:31AM“. However, after declaring necessary libraries, it declares an empty list called date_time and uses the append() function to add the string date to the output list. The execution process executes the date and time using a list comprehension to parse each string date in the date_time list using the parser.parse() function. The resulting datetime objects returns as a list.

However, to return an output in string format, append [0] within square brackets to remove brackets. Here’s how it executes.

#import dateutil Python standard library from parser module
import dateutil
#declare an empty variable to store output value
date_time = []
#using append function
date_time.append('August 14 2023 12:31:00 AM')#if writing AM with space it return brackets at ouput [datetime.datetime(2023, 8, 14, 0, 31)]
#to remove these brackets aooend [0] at the end
#list comprehension using in aggregation with parser module
a=[parser.parse(x) for x in date_time]
b=a[0]
print(b, type(b))
2023-08-14 00:31:00 <class 'datetime.datetime'>

2023-08-14 00:31:00 <class 'datetime.datetime'>

Using dateparser to print string date time

The parse method from the dateparser library is used to parse an input string containing a date and/or time.

The execution process is straightforward. First, you need to install the dateparser library. The parse method will attempt to interpret the input string and return a corresponding Python datetime object.

#install dateparser
pip install dateparser

#import dateparse
import dateparser
#string to be converted
input_string = 'August 14 2023 12:31:00 AM'
#using dateparser with parse attribute
date_time = dateparser.parse(input_string)
print(date_time, type(date_time))
2023-08-14 00:31:00 <class 'datetime.datetime'>

Conclusion

The article demonstrates how to convert a string to a date and time using different approachable methods. The methods used in this tutorial are the following:

  • Using datetime.strptime() to convert a string to a date in Python
    • Print date only in Python
    • How to retrieve time from the strptime() function?
  • Using the Alignment operator ‘=’ with f-string to convert string to date
  • dateutil module to convert string to a date in Python
  • Using list comprehension in aggregation with dateutil and parser module
  • Using dateparser to print string date time

Leave a Comment

Your email address will not be published. Required fields are marked *