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
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")
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
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')
-
len(date.split('-') == 3)
should belen(date.split('-')) == 3
. It may get edited before you see the comment. Commented Oct 4, 2019 at 23:58
You can use something like the following statement:
if variable_name is str:
print('string format!')
else:
print('not a string!')
-
you can print the information and then check if the date is formatted in accordance with the ISO standard(en.wikipedia.org/wiki/ISO_8601). Commented Feb 12, 2018 at 15:58