I am developing a web application with Flask Python. I have a Mysql table with a text column date:
JavaScript
x
7
1
-- date --
2
10/06/2020 18:50:17
3
10/06/2020 18:55:10
4
28/05/2020 22:18:06
5
29/03/2020 20:47:01
6
29/03/2020 21:29:14
7
These data above are date in string format. I need to convert these string dates into format dates.
I did this in python :
JavaScript
1
7
1
actions = Action.query.all() # This is SQLAlchemy request to get all the rows of table 'Action'
2
for action in actions:
3
date=action.date
4
# convert this date string in date format
5
date_time_obj = datetime.strptime(date, '%d/%m/%y %H:%M:%S')
6
print(date_time_obj)
7
But I get this error output:
JavaScript
1
9
1
Traceback (most recent call last):
2
File "j:/Dropbox/cff/Python/folder/test.py", line 18, in <module>
3
date_time_obj = datetime.strptime(date, '%d/%m/%y %H:%M:%S')
4
File "C:UsersNinoAppDataLocalProgramsPythonPython37lib_strptime.py", line 577, in _strptime_datetime
5
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
6
File "C:UsersNinoAppDataLocalProgramsPythonPython37lib_strptime.py", line 359, in _strptime
7
(data_string, format))
8
ValueError: time data '18/02/2020 20:14:31' does not match format '%d/%m/%y %H:%M:%S'
9
I don’t understand as ’18/02/2020 20:14:31′ corresponding perfectly to format ‘%d/%m/%y %H:%M:%S’
What is wrong in my code? Did I miss something?
Advertisement
Answer
You date format should be
JavaScript
1
3
1
from datetime import datetime
2
datetime.strptime(date, '%d/%m/%Y %H:%M:%S')
3
(with Y in upper case)