import datetime
datetime有几个常用类:date time datetime timedelta
1. 今天日期时间
(今天时间)
>>> import datetime
>>> now = datetime.datetime.now()
>>> print now
2014-06-04 21:08:32.952591
(今天日期)
>>> print datetime.date.today()
2014-06-04
2. datetime转化为字符串(strftime)
>>> now = datetime.datetime.now()
>>> now.strftime("%Y-%m-%d")
'2014-06-04'
3. 字符串转化为datetime(strptime)
>>> print datetime.datetime.strptime("2014-06-04 11:11:11", '%Y-%m-%d %H:%M:%S')
2014-06-04 11:11:11
补充--字符串转化为时间戳
timeStamp = int(time.mktime(time.strptime("2014-07-04 15:30:20", "%Y-%m-%d %H:%M:%S")))
补充--时间戳转为字符串
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(1381419600))
补充--当前时间时间戳
currTimestamp = int(time.mktime(time.strptime(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S")))
4. 日期加减操作
在datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别。
构造方法:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
所有的参数都有默认值0,这些参数可以是int或float,正的或负的。
5. 昨天
>>> print datetime.datetime.now() + datetime.timedelta(days = -1)
2014-06-03 21:17:52.026808
6. 明天
>>> print datetime.datetime.now() + datetime.timedelta(days = 1)
2014-06-05 21:18:51.913408
7. 3天后
>>> print datetime.datetime.now() + datetime.timedelta(days = 3)
2014-06-05 21:18:51.913408
8. 日期之差
>>> d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
>>> d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
>>> print d1 - d2
3 days, 0:00:00
9. 判断日期是否相等
if datetime.date.today.strftime("%Y-%m-%d") == "2014-06-05":
print "=="
else:
print "!="
10. 构造日期对象
参数是整数
datetime.date(2014, 6, 3)
详细请看文档:https://docs.python.org/2.7/library/datetime.html