1

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.

1
  • 1
    You're looking for %Y.%m.%d and providing it %Y-%m-%d which doesn't match... Commented Sep 22, 2017 at 13:02

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

because you specified a format of '%Y.%m.%d %H:%M:%S' but you put '-' between the date elements instead of "."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.