Adventures in Machine Learning

Mastering Date and Time in Python with strptime() Function

Converting String to Datetime Using Python strptime() Method

Are you working on a Python project that requires you to work with dates and times? Then you’ve come to the right place! In this article, we’re going to explore how to convert string to datetime using the Python strptime() method.

The strptime() method is used to convert a string representation of a date and time into a Python datetime object. The method is available in both the datetime and time modules in Python.

Syntax and Format Table

The strptime() method takes two main arguments:

  1. String (required) – This is the string representation of the date and time we want to convert.
  2. Format (required) – This is a format string that tells the method how to interpret the string.

The format string uses special codes to represent various parts of the date and time, such as %Y (year), %m (month), %d (day), %H (hour), %M (minute), and %S (second). For example, the format string ‘%Y-%m-%d %H:%M:%S’ would match a string like ‘2022-08-01 14:32:21’.

Common Format Codes

Code Meaning
%Y Year with century (e.g., 2022)
%m Month as a zero-padded decimal (e.g., 08)
%d Day of the month as a zero-padded decimal (e.g., 01)
%H Hour (00 to 23)
%M Minute (00 to 59)
%S Second (00 to 59)

Working with strptime() Method for Datetime and Time Modules

The strptime() method is available in both the datetime and time modules. Let’s see how it works in both.

Example: Converting String to Time Object Using time.strptime()

Suppose we have a string ’14:32:21′ and we want to convert it into a time object. We can use the time.strptime() method to achieve this.

Here’s how we can do it:

import time
time_string = '14:32:21'
time_obj = time.strptime(time_string, '%H:%M:%S')
print(time_obj)

Output:

time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=14, tm_min=32, tm_sec=21, tm_wday=0, tm_yday=1, tm_isdst=-1)

The strptime() method returns a tuple of 9 integers, which we can use to create a time object. The first three integers (tm_year, tm_mon, tm_mday) are set to 1900, since these values are not present in our input string.

Example: Converting String to Datetime Object Using datetime.strptime()

Suppose we have a string ‘2022-08-01 14:32:21’ and we want to convert it into a datetime object. We can use the datetime.strptime() method to achieve this.

Here’s how we can do it:

from datetime import datetime
date_string = '2022-08-01 14:32:21'
date_obj = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
print(date_obj)

Output:

2022-08-01 14:32:21

The strptime() method returns a datetime object, which is what we wanted.

Example: User Input and Formatting Using strptime() and strftime()

Now suppose we want to let the user input a date and time in a particular format, and then we want to convert that string into a datetime object.

We can use the strptime() method for this. Here’s how we can do it:

from datetime import datetime
date_string = input('Enter a date and time (YYYY-MM-DD HH:MM:SS): ')
try:
    date_obj = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
    print('Datetime object:', date_obj)
    # Convert datetime object back to string in a different format
    formatted_date_string = date_obj.strftime('%A, %B %d, %Y at %I:%M %p')
    print('Formatted date string:', formatted_date_string)
except ValueError:
    print('Invalid input!')

Output:

Enter a date and time (YYYY-MM-DD HH:MM:SS): 2022-08-01 14:32:21
Datetime object: 2022-08-01 14:32:21
Formatted date string: Monday, August 01, 2022 at 02:32 PM

This example shows how we can use the strptime() method to convert user input into a datetime object, and then use the strftime() method to format it in a different way. One thing to note is that the strptime() method raises a ValueError if the input string doesn’t match the specified format.

We’ve included a try-except block to handle this case gracefully.

Conclusion

In this article, we learned about the Python strptime() method and its format table, and saw how to use it to convert a string representation of a date and time into a Python datetime object. We also worked with the strptime() method for the datetime and time modules, and saw examples of converting a string to a time or datetime object.

Finally, we saw an example of user input and formatting using strptime() and strftime(). In this article, we explored the Python strptime() method, which is used to convert a string representation of a date and time into a Python datetime object.

We learned about the format table, and saw how to use the strptime() method for both the datetime and time modules. We also looked at examples of converting a string to a time or datetime object, as well as formatting user input using strptime() and strftime().

By understanding how to use the strptime() method, developers can work more effectively with dates and times in their Python projects.

Popular Posts