-1

I have the following code:

from datetime import datetime

date_time_str = '2020-07-17 21:59:49.55'

date_time_obj = datetime.strptime(date_time_str, '%y-%m-%d %H:%M:%S.%f')


print "The type of the date is now",  type(date_time_obj)
print "The date is", date_time_obj

Which results in the err:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    date_time_obj = datetime.strptime(date_time_str, '%y-%m-%d %H:%M:%S.%f')
  File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
    (data_string, format))
ValueError: time data '2020-07-17 21:59:49.553' does not match format '%y-%m-%d %H:%M:%S.%f'

Why cant I convert this date? The following example works:

date_time_str = '18/09/19 01:55:19'
date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')
Martin
  • 1,336
  • 4
  • 32
  • 69
  • 2
    Try `'%Y-%m-%d %H:%M:%S.%f'`, you have the full year in your first example. – ScootCork Jul 28 '20 at 21:16
  • If you have Python 3.7+ available, you can parse much simpler using `datetime.fromisoformat('2020-07-17 21:59:49.55')` since your input is ISO8601 compatible. This method is also [faster than strptime](https://stackoverflow.com/questions/13468126/a-faster-strptime). – FObersteiner Jul 29 '20 at 05:54

1 Answers1

1

First of all, this is not valid Python 3 code. You've used the Python 2 print statement in your code, and trying to run this on Python 3 causes a SyntaxError.

As the error indicates, your date string does not match the format you specified. Take a look at the format codes; the first issue I notice is that you give a 4-digit year (2020) but try to line it up with %y, which is for two-digit year. There may be other issues as well, which should be easy to find looking through that table.

riftEmber
  • 71
  • 7