3

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?

Guisther
  • 59
  • 1
  • 4

4 Answers4

8

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")
Burak Özdemir
  • 510
  • 8
  • 18
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

larsl
  • 338
  • 1
  • 10
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')
Community
  • 1
  • 1
eltonlaw
  • 75
  • 1
  • 7
-2

You can use something like the following statement:

if variable_name is str:
    print('string format!')
else:
    print('not a string!')
Alex Bodnya
  • 120
  • 10
  • you can print the information and then check if the date is formatted in accordance with the ISO standard(https://en.wikipedia.org/wiki/ISO_8601). – Alex Bodnya Feb 12 '18 at 15:58