Reputation: 268
I'm trying to learn the functions of Python but there is one thing I came across which I cannot figure out.
calculated_time = '2014.03.08 11:43:12'
>>> calculated_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
>>> print calculated_time
2017-09-22 15:59:34
Now when I run:
cmpDate = datetime.strptime(calculated_time, '%Y.%m.%d %H:%M:%S')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data '2017-09-22 16:35:12' does not match format'%Y.%m.%d %H:%M:%S'
I can't understand why, if I directly pass this date then it is running but when I pass it after storing in a variable then I've got an error.
Upvotes: 1
Views: 1285
Reputation: 6020
because you specified a format of '%Y.%m.%d %H:%M:%S'
but you put '-' between the date elements instead of "."
Upvotes: 0
Reputation: 54213
They are not the same formats :
'%Y.%m.%d %H:%M:%S'
'%Y-%m-%d %H:%M:%S'
Notice the different separators between year, month and day?
You need to use a consistent datetime format between strftime
and strptime
.
As an example :
>>> from datetime import datetime
>>> datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2017-09-22 15:06:51'
>>> datetime.strptime(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S")
datetime.datetime(2017, 9, 22, 15, 3, 52)
>>> datetime.strptime(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "%Y.%m.%d %H:%M:%S")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/media/steam/anaconda3/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/media/steam/anaconda3/lib/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '2017-09-22 15:03:57' does not match format '%Y.%m.%d %H:%M:%S'
>>> datetime.now().strftime("%Y.%m.%d %H:%M:%S")
'2017.09.22 15:06:55'
>>> datetime.strptime(datetime.now().strftime("%Y.%m.%d %H:%M:%S"), "%Y.%m.%d %H:%M:%S")
datetime.datetime(2017, 9, 22, 15, 4, 3)
Upvotes: 1