您可以通过从matplotlib.dates source复制代码来复制matplotlib.dates.date2num的结果:import datetime
import numpy as np
class _UTC(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(0)
def tzname(self, dt):
return str("UTC")
def dst(self, dt):
return datetime.timedelta(0)
UTC = _UTC()
def date2num(dt):
tzi = getattr(dt, 'tzinfo', None)
if tzi is not None:
dt = dt.astimezone(UTC)
tzi = UTC
base = float(dt.toordinal())
cdate = getattr(dt, 'date', lambda: None)()
if cdate is not None:
midnight_time = datetime.time(0, tzinfo=tzi)
rdt = datetime.datetime.combine(cdate, midnight_time)
base += (dt - rdt).total_seconds() / (60*60*24.)
return base
x1 = datetime.datetime(2015,07,20) # Datetime object without hours, minutes, seconds
x2 = datetime.datetime(2015,07,31,4,50) # Datetime object with hours, minutes
print x1.toordinal() # 735799
print x2.toordinal() # 735810 hours, minutes, seconds get truncated
print date2num(x1) # 735799.0
print date2num(x2) # 735810.201389
import matplotlib.dates
print matplotlib.dates.date2num(x1) # 735799.0
print matplotlib.dates.date2num(x2) # 735810.201389
请注意,如果只使用日期而不使用时间,则转换过程如下所示
x1.toordinal()