4

Using Python, is there a way check if a date field of a document in a MongoDB collection is in ISO format or in string format?

4 Answers 4

12

You can make use of fromisoformat method in datetime library.

from datetime import date

try:
    date.fromisoformat(date_string)
except ValueError:
    print("Invalid isoformat string")
1

You can easily convert a datetime object into a .isoformat() string in Python. The other direction is a bit harder but works as well. Use these code snippets. If they return a datetime object you can be happy.

pip install python-dateutil

then...

import datetime
import dateutil.parser

def getDateTimeFromISO8601String(s):
    d = dateutil.parser.parse(s)
    return d

Check also:

https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

How to convert python .isoformat() string back into datetime object

1

From what I recall, an ISO format is a string so I would do something like:

if len(date.split('-')) == 3: # check if the len is 3. 
    print('ISO string format')
else:
    print('String format')
1
  • len(date.split('-') == 3) should be len(date.split('-')) == 3. It may get edited before you see the comment. Commented Oct 4, 2019 at 23:58
-2

You can use something like the following statement:

if variable_name is str:
    print('string format!')
else:
    print('not a string!')
1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.