How To Convert a String to a DateTime or Time Object in Python
In Python, the `datetime` and `time` modules offer a convenient `strptime()` class method that allows you to convert strings into corresponding objects effortlessly.
Parsing a string into a datetime object with datetime.strptime()
Syntax
datetime.strptime(date_string, format)
The `datetime.strptime()` method returns a `datetime` object corresponding to the `date_string`, interpreting it based on the specified format. It’s important to note that both `date_string` and the format must be provided as string arguments.
The Default Format
'%a %b %d %H:%M:%S %Y'
You can convert a string to a datetime or time object in Python using the datetime module, which provides various functions and classes for working with date and time values. Here’s how you can do it:
Check our developer-friendly Python Hosting!
1. Convert String to datetime.datetime() Object
Python’s standard library includes the datetime module, allowing you to manipulate dates and times effectively. With the help of the datetime class, you can easily transform a string into a datetime object. Let’s break down the fundamental elements in a straightforward manner:
datetime.strptime(date_string, format_string):
This Method takes Two Arguments
date_string: The input string of date or datetime
format_string: A string that specifies the format of the input string. It contains placeholders (format codes) that match the components in the input string.
In the next illustration, a date and time string gets transformed into a `datetime.datetime()` object, and then we display both the class name and the value of the resulting object.
from datetime import datetime
datetime_str = '09/19/23 13:55:26'
format_string = "%m/%d/%y %H:%M:%S"
datetime_object = datetime.strptime(datetime_str, format_string)
print(type(datetime_object))
print(datetime_object)Â # printed in default format
The output is
<class ‘datetime.datetime’>2023-09-19 13:55:2600
%Y: Represents the year
%m: Represents the month as a zero-padded decimal number.
%d: Represents the day of the month as a zero-padded decimal number.
%H: Represents the hour (24-hour clock) as a zero-padded decimal number.
%M: Represents the minute as a zero-padded decimal number.
%S: Represents the second as a zero-padded decimal number.
2. Convert String to datetime.date() Object
You can employ a similar method to extract the time component without the date. In this case, you can use the .time() method on the resultant datetime object to obtain a time object, which solely represents the time part, comprising hours, minutes, seconds, and microseconds. This approach proves valuable when you focus on time-related computations and don’t require the date information.
It’s crucial to ensure that the format string you provide precisely matches the format of your input string. A mismatch will cause the datetime.strptime() method to raise a ValueError exception.
Python’s datetime module equips you with robust tools for managing dates and times, enabling you to efficiently and accurately handle various datetime-related tasks.
As an example, let’s take a look at the following illustration. In this case, a date string is converted into a `datetime.date()` object. The example showcases the resulting object’s class type and its corresponding value:
from datetime import datetime
dateStr = '09-19-2023'
dateObj = datetime.strptime(dateStr, '%m-%d-%Y').date()
print(type(dateObj))
print(dateObj)Â # printed in default format
The output is
<class ‘datetime.date’2023-09-19
3. Convert String to datetime.time() Object
The subsequent illustration showcases the conversion of a time string into a datetime.time() object. It then displays the class type and the value of the resultant object:
from datetime import datetime
time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)
The output is
<class ‘datetime.time’>13:55:26
4. Convert String to datetime.datetime() Object with Locale
The given instance demonstrates the conversion of a date string in a German locale into a datetime.datetime() object. Subsequently, it displays both the class type and the value of the resulting object:
sudo dpkg-reconfigure locales
If ‘en_US.UTF-8’ is unavailable, you can try using a different locale supported on your system. For example, you can use ‘en_US.utf8’ (lowercase ‘utf8’ instead of ‘UTF-8’):
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
date_str_de_DE = '16-Dezember-2022 Freitag'Â # de_DE locale
datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A')
print(type(datetime_object))
print(datetime_object)
The output is
<class ‘datetime.datetime’>2022-12-16 00:00:00
It’s important to highlight that the result does not include the weekday name extracted from the input string. A `datetime.datetime()` object only represents the weekday as a numerical value.
Sign up and avail $100 free credits now!!
5. Converting a String to a struct_time() Object Using time.strptime()
Syntax
time.strptime(time_string[, format])
The `time.strptime()` method generates a `time.struct_time()` object, which is constructed based on the `time_string` and its interpretation according to the provided format. For a precise extraction of time data, it’s crucial that both `time_string` and `format` are supplied as string inputs. If no format is explicitly specified, a default format will be applied.
'%a %b %d %H:%M:%S %Y'
This corresponds to the format returned by the ctime() function.
The format directives remain consistent for both `time.strptime()` and `time.strftime()`. To delve deeper into these format directives for the time module, you can refer to the Python documentation for comprehensive information.
6. Convert String to struct_time() Object With Format Provided
Here’s an example that converts a time string into a `time.struct_time()` object, utilizing the format argument, and subsequently displays the value of the resulting object:
import time
time_str = '11::33::54'
time_obj = time.strptime(time_str, '%H::%M::%S')
print("A time.struct_time object that uses the format provided:")
print(time_obj)
The output is:
A time.struct_time object that uses the format provided:
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1,
tm_hour=11, tm_min=33, tm_sec=54, tm_wday=0, tm_yday=1,
tm_isdst=-1)
The output shows that when you convert a string into a `time.struct_time()` object, the `strptime()` method employs placeholder values for any format directives not specified in the format argument.
Check our developer-friendly Python Hosting!
7. Convert String to struct_time() Object Using Default Format
The default format is applied if you omit the format argument when converting a time string into a `time.struct_time()` object. In this case, an error will be raised if the input string does not precisely match the default format. The default format is:
'%a %b %d %H:%M:%S %Y'
In the following example, a time string is converted into a time.struct_time() object without any format argument and the result is printed:
import time # default format - "%a %b %d %H:%M:%S %Y"
time_str_default = 'Mon Dec 12 14:55:02 2022'
time_obj_default = time.strptime(time_str_default)
print("A time.struct_time object that uses the default format:")
print(time_obj_default)
The output is
A time.struct_time object that uses the default format:
time.struct_time(tm_year=2022, tm_mon=12, tm_mday=12,
tm_hour=14, tm_min=55, tm_sec=2, tm_wday=0, tm_yday=346,
tm_isdst=-1)
In the output, you can see that the strptime() method uses placeholder values for any format instructions not specified in the format argument or in the default format when no format is specified.
8. Troubleshooting strptime() Errors
When the `strptime()` method fails to interpret the input string by the specified format, a ValueError is raised. To detect any parsing errors, one can use a try-except block to observe the output. The ValueError generated by `strptime()` provides detailed information regarding the cause of the parsing issue. The following example outlines some of the more common errors, such as having extra data and format mismatches.
import time
from datetime import datetime
datetime_str = '09/19/18 13:55:26'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve1:
print('ValueError 1:', ve1)
time_str = '99::55::26'
try:
time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as ve2:
print('ValueError 2:', ve2)
The output is
ValueError 1: unconverted data remains:Â 13:55:26
ValueError 2: time data ’99::55::26′ does not match format ‘%H::%M::%S’
Register and get Auto Scalable instances with a Pay-As-You-Go Pricing Model!
Conclusion
Throughout this guide, you learned how to transform date and time strings into datetime and time objects using Python.