It can be easy to run into complications when working with dates, especially when dealing with different formats and time zones. One way to avoid these issues is to use the ISO format, which is widely adopted in various industries. Using a standard format ensures that your code is more easily understood and compatible with other systems. So, using ISO format to represent dates whenever possible is a good practice.
So, before doing a request to the server, you can convert your dates into an ISO format, for example:
yourDate = 'Mon Feb 20 2023 16:07:47 GMT+0100 (Midden-Europese Standard Time)';
yourDateInIsoFormat = (new Date(yourDate)).toISOString();
The resulting string will be 2023-02-20T15:07:47.000Z
.
To parse an ISO format date in Python, you can use the datetime.datetime.fromisoformat()
function. However, there is a small glitch with this approach - only Python 3.11 have full support for all ISO formats. If you're using a version of Python prior to 3.11, you'll need to do a small fix.
Python 3.7 to 3.10:
from datetime import datetime
date_str = '2023-02-20T15:07:47.000Z'
# Replace the "Z" with "+00:00", since fromisoformat does not support UTC timezone offset
date_str = date_str.replace('Z', '+00:00')
# Parse the date string
date = datetime.fromisoformat(date_str)
Python 3.11:
from datetime import datetime
date_str = '2023-02-20T15:07:47.000Z'
# Parse the date string
date = datetime.fromisoformat(date_str)
Also, there is another alternative, use python-dateutil
package:
from dateutil import parser
date_str = "2023-02-20T15:07:47.000Z"
# Parse the date string
date = parser.parse(date_str)
The three options will return a correct date.