How to convert a String to a DateTime object
Posted in Python by Dirk - last update: Feb 08, 2024
To convert a string to a datetime
object in Python, use the datetime.strptime()
method, specifying the string format and desired components.
Introducing the DateTime module
in Python, the datetime module
provides functionalities to work with dates and times. Often, you may need to convert strings representing dates or times into datetime objects for further manipulation or analysis. In this tutorial, we will explore how to convert strings to datetime objects using the datetime.strptime()
method.
The datetime module
in Python provides several classes for working with dates and times. These classes provide a flexible and powerful framework for working with dates and times in Python. By combining them and utilizing their methods, you can perform various operations, calculations, and manipulations with temporal data.
Additionally, the datetime module includes functions for formatting and parsing date and time strings (strftime
and strptime
).
strptime
will be discussed in more detail in the next section.
Here are the main classes in the datetime
module:
datetime.date class
This class represents a date (year, month, day). The syntax to create a date object is datetime.date(year, month, day)
.
Example:
from datetime import date
my_date = date(2024, 2, 7)
print(my_date)
Ouptut:
datetime.time class
It represents a time of day (hour, minute, second, microsecond). The syntax to create a time object is datetime.time(hour, minute, second, microsecond)
.
from datetime import time
my_time = time(12, 30, 45)
print(my_time)
Result:
datetime.datetime class
This combines both date and time components. The syntax to create a datetime object is datetime.datetime(year, month, day, hour, minute, second, microsecond)
.
from datetime import datetime
my_datetime = datetime(2024, 2, 7, 12, 30, 45)
print(my_datetime)
Output:
datetime.timedelta class
This class calculates the difference between two dates or times. Useful for performing arithmetic operations with dates and times.
Example:
from datetime import datetime, timedelta
start_date = datetime(2024, 2, 1)
end_date = datetime(2024, 2, 7)
duration = end_date - start_date
print(duration.days) # prints the number of days between start_date and end_date = 6
Output:
Converting String to DateTime using datetime.strptime()
The datetime.strptime()
method stands for “string parse time” and allows you to convert a string representing a date and time into a datetime object. The syntax is as follows:
datetime.datetime.strptime(date_string, format)
with:
- date_string: The string representing the date and time.
- format: The format of the date and time in the string.
from datetime import datetime
date_string = "2024-02-07 12:30:45"
date_format = "%Y-%m-%d %H:%M:%S"
datetime_object = datetime.strptime(date_string, date_format)
print(datetime_object)
Output:
In this example, date_string
represents the date and time in a specific format, and date_format
specifies the format of the string. The resulting datetime_object
will be a datetime object representing the provided date and time.
Here are some commonly used format codes:
%Y
: Four-digit year (e.g. 2022)
%y
: Two-digit year, without century (e.g. 22)
%m
: Month (01-12)
%B
: Full month name (e.g., January)
%b
: Abbreviated month name (e.g., Jan)
%d
: Day of the month (01-31)
%A
: Full weekday name (e.g., Monday)
%a
: Abbreviated weekday name (e.g., Mon)
%w
: Weekday as Number, range 0 to 6, Sunday being 0
%u
: Weekday as Number, range 1 to 7, Monday being
%H
: Hour (00-23)
%I
: Hour (01-12)
%p
: AM/PM
%M
: Minute (00-59)
%S
: Second (00-59)
A more exhaustive list can be found here
Potential Issues and Solutions
If the format in datetime.strptime()
does not match the actual format of the date string, a ValueError
will be raised.
# Incorrect format example
date_string = "2024-02-07"
date_format = "%Y/%m/%d" # Incorrect format
# This will raise a ValueError
datetime_object = datetime.strptime(date_string, date_format)
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2024-02-07' does not match format '%Y/%m/%d'
Solution: ensure that the format matches the structure of your date string.
ValueError: day is out of range for month - Invalid Date
If the date string itself contains an invalid date (e.g., “2024-02-30”), a ValueError
will be raised.
# Invalid date example
date_string = "2024-02-30"
date_format = "%Y-%m-%d"
# This will raise a ValueError
datetime_object = datetime.strptime(date_string, date_format)
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/_strptime.py", line 534, in _strptime
julian = datetime_date(year, month, day).toordinal() - \
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: day is out of range for month
Solution: make sure that the input date string represents a valid date.
TypeError: strptime() argument 1 must be str, not int
If you attempt to pass an integer directly to datetime.strptime()
as the date_string parameter, it will result in a TypeError.
from datetime import datetime
result = datetime.strptime(20240207, "%Y%m%d")
Result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: strptime() argument 1 must be str, not int
The strptime
method expects a string as its first argument, not an integer. To fix this, first convert the integer to a string using the str()
function
from datetime import datetime
integer_date = 20240207
date_string = str(integer_date)
result = datetime.strptime(date_string, "%Y%m%d")
print(result)
Output:
ValueError: unconverted data remains
This ValueError
typically occurs when the provided date string contains extra characters that were not consumed by the format specified. This happens when the date string has more characters than expected based on the provided format.
Example:
from datetime import datetime
date_string = "20240207123045extra"
result = datetime.strptime(date_string, "%Y%m%d%H%M%S")
print(result)
In this example, the date_string has additional characters (“extra”) after the expected date and time components.
This will give the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/_strptime.py", line 352, in _strptime
raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: extra
The ValueError: unconverted data remains: extra
is raised by strptime
as it cannot match those extra characters with the specified format.
Solution: To fix this issue, make sure that the date string exactly matches the format provided to strptime
. If there are additional characters that are not part of the date and time components, they should be removed or adjusted in the input string or the format string accordingly.
Other articles