【发布时间】:2018-07-22 20:14:49
【问题描述】:
使用 Python,有没有办法检查 MongoDB 集合中文档的 date 字段是 ISO 格式还是字符串格式?
【问题讨论】:
标签: python mongodb pymongo iso
使用 Python,有没有办法检查 MongoDB 集合中文档的 date 字段是 ISO 格式还是字符串格式?
【问题讨论】:
标签: python mongodb pymongo iso
你可以使用datetime库中的fromisoformat方法。
from datetime import date
try:
date.fromisoformat(date_string)
except ValueError:
print("Invalid isoformat string")
【讨论】:
您可以在 Python 中轻松地将日期时间对象转换为 .isoformat() 字符串。另一个方向有点困难,但也有效。使用这些代码 sn-ps。如果他们返回一个日期时间对象,你会很高兴。
pip install python-dateutil
那么……
import datetime
import dateutil.parser
def getDateTimeFromISO8601String(s):
d = dateutil.parser.parse(s)
return d
也检查一下:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
How to convert python .isoformat() string back into datetime object
【讨论】:
据我回忆,ISO 格式是一个字符串,所以我会这样做:
if len(date.split('-')) == 3: # check if the len is 3.
print('ISO string format')
else:
print('String format')
【讨论】:
len(date.split('-') == 3) 应该是 len(date.split('-')) == 3。在您看到评论之前,它可能会被编辑。
你可以使用类似下面的语句:
if variable_name is str:
print('string format!')
else:
print('not a string!')
【讨论】: