Python date 类型转 datetime 类型

datetime to date

在 Python 中,通过 datetime 获取到日志的 date 类型比较简单, datetime 提供了 date() 方法

In [1]: from datetime import datetime
In [2]: help(datetime.date)

In [3]: datetime.now()
Out[3]: datetime.datetime(2017, 6, 22, 10, 49, 22, 95457)

In [4]: datetime.now().date()
Out[4]: datetime.date(2017, 6, 22)

datetime date 比较

再看看下面一个例子

# coding:utf-8
# python2.7
# Convert date to datetime in Python
from datetime import datetime

today = datetime.now().date()
todaytime = datetime.now()

print today == todaytime
print today > todaytime

运行之后这样的

# python datetime_date_comp.py
Traceback (most recent call last):
  File "datetime_date_comp.py", line 8, in <module>
    today > todaytime
TypeError: can't compare datetime.datetime to datetime.date

datetime 和 date 不能进行 大小比较, 就有一个把 date 类型转成 datetime 类型的需求了

date to datetime

下面是几种方式

from datetime import datetime, date

d = date.today()
print datetime.combine(d, datetime.min.time())
print datetime.fromordinal(d.toordinal())
print datetime(d.year, d.month, d.day)
print datetime(*d.timetuple()[:-4])

simple test

In [8]: %time datetime(*d.timetuple()[:-4])
CPU times: user 10 µs, sys: 0 ns, total: 10 µs
Wall time: 25 µs
Out[8]: datetime.datetime(2017, 6, 22, 0, 0)

In [9]: %time datetime(d.year, d.month, d.day)
CPU times: user 5 µs, sys: 1 µs, total: 6 µs
Wall time: 16 µs
Out[9]: datetime.datetime(2017, 6, 22, 0, 0)

In [10]: %time datetime.fromordinal(d.toordinal())
CPU times: user 6 µs, sys: 0 ns, total: 6 µs
Wall time: 8.11 µs
Out[10]: datetime.datetime(2017, 6, 22, 0, 0)

In [11]: %time datetime.combine(d, datetime.min.time())
CPU times: user 8 µs, sys: 4 µs, total: 12 µs
Wall time: 11 µs
Out[11]: datetime.datetime(2017, 6, 22, 0, 0)

看起来 datetime(d.year, d.month, d.day) 这种方式更好一些。

你可能感兴趣的:(如今Python)