Python的type 还是要靠isinstance判断类型
2015-10-12 23:17
911 查看
今天处理数据库内容迁移,碰到时间数据类型无法使用type判断出来的情况
背景知识
datetime模块中的datetime类的实例可以表示一个时刻(日期,以及这个日期中的特定时间),可以不包含时区或者包含时区,并总是忽略闰秒。
打印不出来是因为datetime是module的类型,压根不是类,但是type里面不进行类型检查,新手很容易犯错,后来使用了isinstance,程序报错才发现datetime不行,那个错误的代码
立马加上类!
背景知识
datetime模块中的datetime类的实例可以表示一个时刻(日期,以及这个日期中的特定时间),可以不包含时区或者包含时区,并总是忽略闰秒。
import datetime
test = datetime.datetime(2015,10,12,23,0,0) if test in (int,float,datetime): print('ok')这里ok打印不出来的,后来测试了下type才知道
>>> type(test) <type 'datetime.datetime'>
打印不出来是因为datetime是module的类型,压根不是类,但是type里面不进行类型检查,新手很容易犯错,后来使用了isinstance,程序报错才发现datetime不行,那个错误的代码
>>> if isinstance(test,datetime): ... print('ok') ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
立马加上类!
>>> if isinstance(test,datetime.datetime): ... print('ok') ... ok
相关文章推荐
- python 小知识点
- python函数特点NO.1
- [原创]如何编写多个阻塞队列连接下的多生产者多消费者的Python程序
- LeetCode----Single Number
- python获取新浪新闻
- 【Python】爬虫入门--抓取网站图片
- [LeetCode]题解(python):023-Merge k Sorted Lists
- Python Scapy(2.3.1)文档学习(七):故常排除
- 【Python之旅】第六篇(六):Python多进程使用
- Python Lambda表达式
- 简单的Python爬虫程序
- [LeetCode]题解(python):022-Generate Parentheses
- [转]python对json的相关操作
- [转]Python中的with…as…
- Python标准库--os模块
- 堆排序学习笔记及堆排序算法的python实现
- [LeetCode]题解(python):021-Merge Two Sorted Lists
- 八皇后问题(Python实现)
- 如何用Python实现任一个英文的纯文本文件,统计其中的单词出现的个数?
- python编码问题初探