【问题标题】:How can I check if a date field is in ISO format?如何检查日期字段是否为 ISO 格式?
【发布时间】:2018-07-22 20:14:49
【问题描述】:

使用 Python,有没有办法检查 MongoDB 集合中文档的 date 字段是 ISO 格式还是字符串格式?

【问题讨论】:

    标签: python mongodb pymongo iso


    【解决方案1】:

    你可以使用datetime库中的fromisoformat方法。

    from datetime import date
    
    try:
        date.fromisoformat(date_string)
    except ValueError:
        print("Invalid isoformat string")
    

    【讨论】:

      【解决方案2】:

      您可以在 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

      【讨论】:

        【解决方案3】:

        据我回忆,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。在您看到评论之前,它可能会被编辑。
        【解决方案4】:

        你可以使用类似下面的语句:

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

        【讨论】:

        猜你喜欢
        • 2023-03-29
        • 1970-01-01
        • 2021-10-23
        • 1970-01-01
        • 2023-04-11
        • 2011-10-06
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多