Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ValueError: unconverted data remains:

Tags:

python

time

I have the following code:

This is my Code:

print (start_timestamp)
start_timestamp_no_iso = datetime.strptime(start_timestamp, "%Y-%m-%dT%H:%M:%S.%f")

This is what I get:

INFO - 2018-11-20T14:44:03.452131
INFO - Traceback (most recent call last):
INFO - File "/home/ubuntu/script.py", line 84, in <module>
INFO - start_timestamp_no_iso = datetime.strptime(start_timestamp, "%Y-%m-%dT%H:%M:%S.%f")
INFO - File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
INFO - tt, fraction = _strptime(data_string, format)
INFO - File "/usr/lib/python3.6/_strptime.py", line 365, in _strptime
INFO - data_string[found.end():])
INFO - ValueError: unconverted data remains:
INFO - Command exited with return code 1

I understand what it means but I don't understand why it happens. I simply convert the timestamp from iso format to non iso. What is the problem?

like image 761
Luis Avatar asked Dec 04 '18 07:12

Luis


People also ask

What is the difference between Strftime and Strptime in Python?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

How do I convert datetime to string in Python?

To convert datetime to string in Python, use the strftime() function. The strftime() method is a built-in method that returns the string representing date and time using date, time, or datetime object.

How do I remove the time from a date in Python?

To remove the time from a datetime object in Python, convert the datetime to a date using date(). You can also use strftime() to create a string from a datetime object without the time.


1 Answers

Your format string %Y-%m-%dT%H:%M:%S.%f is absolutely correct. I am sure, you have line feeds at the end of your line. Try

start_timestamp_no_iso = datetime.strptime(start_timestamp.strip(' \t\r\n'), "%Y-%m-%dT%H:%M:%S.%f")
like image 132
grapes Avatar answered Oct 18 '22 22:10

grapes