Datetime strptime error

If you want to format a datetime using datetime.strptime(), the format needs to match the original string. If there is a mismatch between the format and

If you want to format a datetime using datetime.strptime(), the format needs to match the original string. If there is a mismatch between the format and the original string, strptime will not be able to parse the string and will raise the ValueError: unconverted data remains.

To solve this error, ensure that the format you are using matches the string you want to parse.

This tutorial will go through the error in detail and how to solve it with code examples.


Table of contents

  • Python ValueError: unconverted data remains
  • Example
    • Solution
  • Format Code List
  • Summary

Python ValueError: unconverted data remains

In Python, a value is a piece of information stored within a particular object. We will encounter a ValueError in Python when using a built-in operation or function that receives an argument that is the right type but an inappropriate value. In this specific error, the data we pass to the datetime.strptime() method is the correct type, string, but has an incorrect format.

The strptime method is available in the DateTime module and formats a timestamp in string format to a datetime object. The syntax of the method is as follows:

datetime.strptime(date_string, format)

Parameters

  • date_string: Required. String to convert to datetime object.
  • format: Required. Format code

Returns

The method returns a datetime object corresponding to date_string, parsed according to format.

ValueError is raised if time.strptime() cannot parse date_string and format.

Example

Let’s look at an example where we want to convert a string representing a string to a datetime object.

from datetime import datetime

# Define date string

date_string = '19 March, 2021 21:23'

# Convert date string to datetime object

date_object = datetime.strptime(date_string, "%d %B, %Y")

print(date_object)

Let’s run the code to see what happens:

~/opt/anaconda3/lib/python3.8/_strptime.py in _strptime(data_string, format)
    350                          (data_string, format))
    351     if len(data_string) != found.end():
--> 352         raise ValueError("unconverted data remains: %s" %
    353                           data_string[found.end():])
    354 

ValueError: unconverted data remains:  21:23

The error occurs because the part of the string ‘21:23‘ does not match the format_code ‘%d %B, %Y

Solution

To solve this error we need to include hours and minutes in the format code. The format code for hours is %H and for minutes is %M. Let’s look at the revised code:

from datetime import datetime

# Define date string

date_string = '19 March, 2021 21:23'

# Convert date string to datetime object

date_object = datetime.strptime(date_string, "%d %B, %Y %H:%M")

print(date_object)

Let’s run the code to see the result:

2021-03-19 21:23:00

We successfully converted the string to a datetime object using datetime.strptime().

Format Code List

Format code Meaning Example
%a Abbreviated weekday name Sun, Mon,…
%A Full weekday name Sunday, Monday, …
%w Weekday as a decimal number 0, 1, …, 6
%d Day of the month as a zero-padded decimal 01, 02, …, 31
%-d Day of the month as a decimal number 1, 2, …, 30
%b Abbreviated month name Jan, Feb, …, Dec
%B Full month name January, February, …
%m Month as a zero-padded decimal number 01, 02, …, 12
%-m Month as a decimal number 1, 2, …, 12
%y Year without century as a zero-padded decimal number 00, 01, …, 99
%-y Year without century as a decimal number 0, 1, …, 99
%Y Year with century as a decimal number 2013, 2014, …
%H Hour (24-hour clock) as a zero-padded decimal number 00, 01, …, 23
%-H Hour (24-hour clock) as a decimal number 0, 1, …, 23
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, …, 12
%-I Hour (12-hour clock) as a zero-padded decimal number 1, 2, …, 12
%p Locale’s AM or PM AM, PM
%M Minute as a zero-padded decimal number 00, 01, …, 59
%-M Minute as a decimal number 0, 1, …, 59
%S Second as a zero-padded number 00, 01, …, 59
%-S Second as a decimal number 0, 1, …, 59
%f Microsecond as a decimal number, zero-padded on the left 000000 – 999999
%z UTC offset in the form +HHMM or -HHMM
%Z Time zone name
%j Day of the year as a zero-padded decimal number 001, 002, …, 366
%-j Day of the year as a decimal number 1, 2, …, 366
%U Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are in week 0 00, 01, …, 53
%W Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are in week 0 00, 01, …, 53
%c Locale’s appropriate date and time representation Mon Apr 11 08:56:02 2022
%x Locale’s appropriate date representation 04/11/22
%X Locale’s appropriate time representation 08:56:02
%% A Literal ‘%’ character %
Table of format codes for datetime.strptime

Summary

Congratulations on reading to the end of this tutorial! The ValueError: unconverted data remains occurs when the string has a format that does not match the format code of the datetime.strptime() method.

For further reading on datetime objects, go to the article: How to Solve Python AttributeError: ‘Series’ object has no attribute ‘strftime’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Here is my Transaction class:

class Transaction(object):
    def __init__(self, company, num, price, date, is_buy):
        self.company = company
        self.num = num
        self.price = price
        self.date = datetime.strptime(date, "%Y-%m-%d")
        self.is_buy = is_buy

And when I’m trying to run the date function:

tr = Transaction('AAPL', 600, '2013-10-25')
print tr.date

I’m getting the following error:

   self.date = datetime.strptime(self.d, "%Y-%m-%d")
 AttributeError: 'module' object has no attribute 'strptime'

How can I fix that?

Aran-Fey's user avatar

Aran-Fey

37.9k11 gold badges99 silver badges143 bronze badges

asked Oct 20, 2013 at 16:45

Michael's user avatar

2

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

answered Oct 20, 2013 at 16:46

4

Use the correct call: strptime is a classmethod of the datetime.datetime class, it’s not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case you’re facing (in the future), look at your import statements

  • import datetime: that’s the module (that’s what you have right now).
  • from datetime import datetime: that’s the class.

answered Oct 20, 2013 at 16:46

Thomas Orozco's user avatar

Thomas OrozcoThomas Orozco

51.9k9 gold badges110 silver badges115 bronze badges

1

I got the same problem and it is not the solution that you told. So I changed the «from datetime import datetime» to «import datetime». After that with
the help of «datetime.datetime» I can get the whole modules correctly. I guess this is the correct answer to that question.

answered Mar 14, 2020 at 22:42

Kursad's user avatar

KursadKursad

1031 silver badge6 bronze badges

Values ​​may differ depending on usage.

import datetime
date = datetime.datetime.now()
date.strftime('%Y-%m-%d') # date variable type is datetime

The value of the date variable must be a string::

date = '2021-09-06'
datetime.datetime.strptime(date, "%Y-%m-%d")
str(datetime.datetime.strptime(date, "%Y-%m-%d")) # show differently

answered Sep 6, 2021 at 6:34

Ayse's user avatar

AyseAyse

5073 silver badges11 bronze badges

The solutions mentioned by the others are correct. But for me, it was a problem with another library importing datetime module for me and overriding the datetime class I was importing.
an example with tsai library:

from datetime import datetime
from tsai.all import *

This will give you the error: 'module' object has no attribute 'strptime'.

In this case, just flip the order of imports or just don’t import everything (even if the documentation does that) :

from tsai.all import *
from datetime import datetime

answered Dec 19, 2022 at 15:25

bibs2091's user avatar

bibs2091bibs2091

111 silver badge3 bronze badges

Table of Contents
Hide
  1. What is AttributeError: ‘module’ object has no attribute ‘strptime’
  2. How to resolve AttributeError: ‘module’ object has no attribute ‘strptime’
    1. Solution 1: Import the datetime module directly and access the method through its class name
    2. Approach 2 – Import the datetime class from the datetime module
  3. Conclusion

The AttributeError: ‘module’ object has no attribute ‘strptime’ occurs if you have imported the datetime module and directly if we are using the datetime.strptime() method on the datetime module. 

The datetime is a module, and it does not have the strptime() method; instead, we need to use the datetime class name, which has the method correct method and the syntax for the same is datetime.datetime.strptime() 

In this tutorial, we will look into what exactly is AttributeError: ‘module’ object has no attribute ‘strptime’ and how to resolve the error with examples.

First, let us see how to reproduce this issue and why developers face this particular issue with a simple example.

# import datetime module
import datetime

start_date = "2022-05-06"

# convert into datetime object and print
print(datetime.strptime(start_date, "%Y-%m-%d"))

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodeCode.py", line 7, in <module>
    print(datetime.strptime(start_date, "%Y-%m-%d"))
AttributeError: module 'datetime' has no attribute 'strptime'

In the above example, we are importing the datetime module and trying to convert the string datetime to a datetime object using the datetime.strptime() method.

When we run the code, we get an AttributeError: module ‘datetime’ has no attribute ‘strptime’

The issue occurs because the datetime module does not have a strptime() method, and hence it is throwing an error.

The datetime module has a class name called datetime which in turn has the method strptime()

Since the module name and class name are also the same, it leads to a lot of confusion for the new developers, and they feel it’s ambiguous to use datetime multiple times.

How to resolve AttributeError: ‘module’ object has no attribute ‘strptime’

We can resolve the ‘module’ object has no attribute ‘strptime’ by using the strptime() method, which is present inside the datetime class.

There are two ways to access the strptime() method correctly.

Solution 1: Import the datetime module directly and access the method through its class name

If you are importing the datetime module directly, then the best way to resolve the error is to use datetime.datetime.strptime() method.

Syntax

datetime.datetime.strptime()

Here the first datetime is a module and the second datetime is a class which has a method strptime()

Example – 

# import datetime module
import datetime

start_date = "2022-05-06"

# convert into datetime object and print
print(datetime.datetime.strptime(start_date, "%Y-%m-%d"))

Output

2022-05-06 00:00:00

Approach 2 – Import the datetime class from the datetime module

Another way to resolve the issue is to import the datetime class directly using the syntax from datetime import datetime

Syntax

from datetime import datetime

While using the from syntax, we import the datetime class directly and using the class name; we can access all of its methods. We do not have to prefix/use the module name here.

Example –

# import datetime class from datetime module
from datetime import datetime

start_date = "2022-05-06"

# convert into datetime object and print
print(datetime.strptime(start_date, "%Y-%m-%d"))

Output

2022-05-06 00:00:00

Conclusion

The datetime module does not have the strptime() method; hence if we try to use datetime.strptime() directly we get AttributeError: ‘module’ object has no attribute ‘strptime’

We can resolve the issue using the datetime class name instead of the datetime module. An alternate way is to import the datetime class using the from keyword directly.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Продолжаем цикл статей по управлению датой и временем. На прошлых уроках, мы прошли вводный курс по модулю DateTime, и методу strftime. Сегодня разберем на примерах, как создать объект DateTime из строки.

Метод для создания объекта из строки strptime(). Важно понимать, что мы не можем создавать объект DateTime из любой строки, строка должна иметь определенный формат.

Пример 1. Объект string для DateTime

                    
from datetime import datetime

date_s = "11 June, 2021"

print("date_s =", date_s)
print("Тип date_s =", type(date_s))

date_object = datetime.strptime(date_s, "%d %B, %Y")

print("date_object =", date_object)
print("Тип date_object =", type(date_object))

Результат:

date_s = 11 June, 2021
type of date_s = <class 'str'>
date_object = 2021-06-11 00:00:00
type of date_object = <class 'datetime.datetime'>

Функция strptime принимает два аргумента:

  • Строка (которая в итоге преобразуется в дату и время)
  • Код формата (все коды формата описаны ниже)

Основываясь на этих двух аргументах, при их правильном формате, метод вернет нам объект DateTime.  Разберем визуализацию выше приведенного примера.

python strptime

  • %d — День месяца (01,02,….31)
  • %B — Название месяца (Январь, Февраль….Декабрь)
  • %Y -Год из четырех цифр (2018,2019,…2021)

Пример 2. Объект string DateTime

                    
from datetime import datetime

dt_s = "12/11/2020 09:15:32"

# Считываем дату в формате dd/mm/yyyy format
dt_object1 = datetime.strptime(dt_s, "%d/%m/%Y %H:%M:%S")
print("dt_object1 =", dt_object1)

# Считываем дату в формате mm/dd/yyyy format
dt_object2 = datetime.strptime(dt_s, "%m/%d/%Y %H:%M:%S")
print("dt_object2 =", dt_object2)

Результат:
dt_object1 = 2018-11-12 09:15:32
dt_object2 = 2018-12-11 09:15:32

Список кодов strptime()

Директива Значение Пример
%a Сокращенное название дня недели. Вс.Пн.Вт
%A Полное название дня недели. Воскресенье, понедельник
%w День недели в виде десятичного числа. 0,1,2,3,4,5,6
%d День месяца в с добавлением нуля. 01,02,03,….31
%-d День месяца в виде числа. 1,2,3,4,5….31
%b Сокращенное название месяца. Янв.Февр,Мар
%B Полное название месяца. Январь, февраль, Март
%m Месяц в виде числа с нулевым заполнением. 01,02,03…12
%-m Месяц в виде десятичного числа. 1,2,3,…12
%y Год без столетия как десятичное число с нулевой подкладкой. 01,02,03…99
%-y Год без столетия как десятичное число. 1,2,3,…99
%Y Год с веком в виде десятичного числа. 2010,2011,…2021
%H Час (24-часовые часы) с нулевым заполнением. 00,01,02,…23
%-H Час (24-часовые часы) как десятичное число. 1,2,3,…23
%I Час (12-часовые часы) с нулевым заполнением. 01,02,03,…12
%-I Час (12-часовые часы) как десятичное число. 1,2,3…12
%p AM/PM
%M Минута в виде числа с нулевым заполнением. 00,01,02,…59
%-M Минута как десятичное число. 1,2,3,…59
%S Секунды с нулевым заполнением 00,01,02,…59
%-S Секунды как десятичное значение 0,1,2,3…59
%f Микросекунда в виде десятичного числа, слева-ноль. 000000-999999
%z Смещение UTC в виде +HHMM или -HHMM.
%Z Название часового пояса.
%j День года в виде десятичного числа, дополненного нулем. 001,002,003,…366
%-j День года в виде десятичного числа. 1,2,3,….366
%U Номер недели года (воскресенье как первый день недели). Все дни в новом году, предшествующие первому воскресенью, считаются неделей 0. 00,01,02,..53
%W Номер недели года (понедельник как первый день недели). Все дни в новом году, предшествующие первому понедельнику, считаются неделей 0. 00,01,02,..53
%c Соответствующее представление даты и времени локали. Пн 30 сентября 07:06:05 2013
%x Соответствующее представление даты локали. 09/30/13
%X Соответствующее представление времени локали. 07:06:05
%% Буквальный символ»%». %

ValueError в strptime()

Мы с вами уже определились, что строка передаваемая в качестве аргумента, должна иметь определенный формат. В случае если переданные аргументы в strptime() некорректны, то мы получим ошибку ValueError. Наример:

                    
from datetime import datetime

date_s = "12/11/2018"
date_object = datetime.strptime(date_s, "%d %m %Y")

print("date_object =", date_object)

Результат:
ValueError: time data '12/11/2018' does not match format '%d %m %Y'

In this Python article, we will discuss the use of strptime function, and how to use this to convert string to a datetime object. We will also discuss various examples to understand the concept better. Let’s get started.

1. What is the use of datetime strptime in Python?

We use the function or method strptime() to convert a provided string into a DateTime object. The condition is that the string should be a valid representation of datetime.

The datetime.strptime() function intakes a time signifying string in different formats; a struct_time is returned in either gmtime() format or localtime() format.

The strptime takes the parameter similar to directives used by strftime function. The default format is “%a %b %d %H:%M:%S %Y”, its formatting is the same that is returned by ctime().

When the provided string format is invalid or when the parsed value has too much data then ValueError is thrown.

Syntax:
time.strptime(string[, format])
#or
datetime.strptime(date_string, format)

Parameters

  • string − The input time string which is parsed and converted to the object.
  • format − To parse the provided string, format directive is used.

According to the provided string and format code, the strptime() function returns an equivalent datetime object.


2. Different format Code List

Directive Specification Output
%a used for an abbreviated name for weekdays Sun, Mon, …, Sat
%A used for the full name of a weekday Sunday, Monday, …, Saturday
%w used to represent the weekday in whole numbers with 0 as of Sunday and 6 as of Saturday and other values in between as different weekdays. 0, 1, 2, 3, 4, 5, 6
%d used to represent the day of a month in a zero-padded number way. 01, 02, …, 31
%b used to represent the abbreviated name for the month. Jan, Feb, …, Dec
%B used to represent the full name for the month. January, February, …, December
%m used to represent the month in a zero-padded number way. 01, 02 … 12
%y used to represent a specific year as a zero-padded decimal number without displaying the century. 01, 02, … 99
%Y used to represent a specific year as a decimal number with displaying the century. 0001, 0002, … , 9999
%H used to represent the hour in the 24-hour clock format in a zero-padded decimal number way. 01, 02, … , 23
%I used to represent the hour in the 12-hour clock format in a zero-padded decimal number way. 01, 02, … , 12
%p used to represent AM or PM. AM, PM (en_US)
%M used to represent the minute in a zero-padded decimal number way. 01, 02, … , 59
%S used to represent the second in a zero-padded decimal number way. 01, 02, … , 59
%f used to represent the Microsecond in a zero-padded decimal number way to its left. 000000, 000001, …, 999999
Not applicable with time module.
%z used to represent the ±HHMM[SS] calculated from the UTC according to the local time. (naive object returns an empty string). (empty), +0000, -0400, +1030
%Z used to represent the name of the time zone. (empty), UTC, IST, CST
%j used to represent the particular day of the year in a zero-padded decimal number way. 001, 002, …, 366
%U used to represent the particular week number of the year in a zero-padded decimal number way.
After a new year, days after the first Sunday are marked to be in week 0.
00, 01, …, 53
%W used to represent the particular week number of the year in a zero-padded decimal number way.
After a new year, days after the first Monday are marked to be in week 0.
00, 01, …, 53
%c used to represent the local appropriate date and time. Tue Aug 16 21:30:00 1988
%x used to represent the local appropriate date. 08/16/88 (None)
08/16/1988
%X used to represent the local appropriate time. 21:30:00
%% used to represent a “%” character as a literal. %
List of all useful formats for strptime function

3. datetime.strptime examples in Python

Let’s take some examples in different programs to see how to use them.

import datetime

provided_datetime_string_1 = "05/07/2021 12:15:32"

f1 = datetime.datetime.strptime(provided_datetime_string_1, "%d/%m/%Y %H:%M:%S")
print("format1 =", f1)

f2 = datetime.datetime.strptime(provided_datetime_string_1, "%m/%d/%Y %H:%M:%S")
print("format2 =", f2)
Output
format1 = 2021-07-05 12:15:32
format2 = 2021-05-07 12:15:32
import time
print(time.strptime('Fri Jul 05 13:01:02 2021'))
Output
time.struct_time(tm_year=2021, tm_mon=7, tm_mday=5, tm_hour=13, tm_min=1, tm_sec=2, tm_wday=4, tm_yday=186, tm_isdst=-1)
import datetime

string = '12::17::39'
f1 = datetime.datetime.strptime(string, '%H::%M::%S').time()
print(type(f1))
print(f1)
Output
12:17:39

3. ValueError in datetime strptime()

When the string provided by the user and the prescribed format code in the strptime() function doesn’t match then an error is generated which is ValueError.

Read more about errors and error handling in Python

import datetime

string = '12::two minutes::39'
f1 = datetime.datetime.strptime(string, '%H::%M::%S').time()
print(f1)
Output
Traceback (most recent call last):
File "main.py", line 4, in 
f1 = datetime.datetime.strptime(string, '%H::%M::%S').time()
File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '12::two minutes::39' does not match format '%H::%M::%S'

We can remove such errors using exception handling by catching the exception and correcting it.

Let’s do it on one other example. Try the above yourself after watching one.

import datetime
import time

input_string_1 = '07/2021/05 12:45:49'

try:
  object1 = datetime.datetime.strptime(input_string_1, '%m/%d/%y')
except ValueError as exception:
  print('Error Raised: ', exception)

input_string_2 = '99::55::26'

try:
  object2 = time.strptime(input_string_2, '%H::%M::%S')
except ValueError as exception:
  print('Error Raised: ', exception)
Output
Error Raised:  time data '07/2021/05 12:45:49' does not match format '%m/%d/%y'
Error Raised:  time data '99::55::26' does not match format '%H::%M::%S'

4. Conclusion

Finally, if we sum up, in this article we learned everything about the strptime function/method. We covered how to use and why to use the strptime function for milliseconds and different input formats, we also covered:

  • What is the use of Strptime in python and how to use the strptime in python
  • Different format Code List for the strptime function/method
  • ValueError in strptime() and how to remove the valueerror in strptime() fucntion

Read More: We recommend going through another article to convert a datetime object to formatted string using strftime()


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended —

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Dateizugriff verweigert omsi 2 как исправить
  • Connecting cs go network как исправить
  • Date timezone error a valid timezone that matches mysql and the system
  • Configure error library crypto not found install openssl
  • Copy partition error code 40

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии