>我有以下内容:
> date1
Timestamp('2014-01-23 00:00:00', tz=None)
> date2
datetime.date(2014, 3, 26)
我读到这个答案,我可以使用pandas.to_datetime()
从Timestamps
转换为datetime
对象,但它似乎不起作用:
> pd.to_datetime(date1)
Timestamp('2014-01-23 00:00:00', tz=None)
为什么?如何在这两种格式之间进行转换?
您可以使用 to_pydatetime 方法更明确:
In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)
In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)
它也在DatetimeIndex上可用:
In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')
In [14]: rng.to_pydatetime()
Out[14]:
array([datetime.datetime(2011, 1, 10, 0, 0),
datetime.datetime(2011, 1, 11, 0, 0),
datetime.datetime(2011, 1, 12, 0, 0)], dtype=object)
Pandas Timestamp to datetime.datetime:
pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()
datetime.datetime to Timestamp
pd.Timestamp(datetime(2014, 1, 23))
>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')
要回答从现有的python日期时间到熊猫时间戳的问题,请执行以下操作:
import time, calendar, pandas as pd
from datetime import datetime
def to_posix_ts(d: datetime, utc:bool=True) -> float:
tt=d.timetuple()
return (calendar.timegm(tt) if utc else time.mktime(tt)) + round(d.microsecond/1000000, 0)
def pd_timestamp_from_datetime(d: datetime) -> pd.Timestamp:
return pd.to_datetime(to_posix_ts(d), unit='s')
dt = pd_timestamp_from_datetime(datetime.now())
print('({}) {}'.format(type(dt), dt))
输出:
(<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2020-09-05 23:38:55
我希望有一种更优雅的方式来做到这一点,但to_posix_ts
已经在我的标准工具链中,所以我继续前进。