kil*_*les 37 python datetime timestamp pandas
我有一个Pandas列的Timestamp数据
In [27]: train["Original_Quote_Date"][6]
Out[27]: Timestamp('2013-12-25 00:00:00')
Run Code Online (Sandbox Code Playgroud)
如何检查这些对象与datetime.date该类型对象的等价性
datetime.date(2013, 12, 25)
Run Code Online (Sandbox Code Playgroud)
And*_*den 41
使用.date方法:
In [11]: t = pd.Timestamp('2013-12-25 00:00:00')
In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)
In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True
Run Code Online (Sandbox Code Playgroud)
要与DatetimeIndex(即时间戳数组)进行比较,您需要以相反的方式执行此操作:
In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')
In [22]: ts = pd.DatetimeIndex([t])
In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)
Run Code Online (Sandbox Code Playgroud)
Xav*_* Ho 14
从pandas 0.20.3开始,用于.to_pydatetime()将任何pandas.DateTimeIndex实例转换为Python datetime.datetime.
您可以将 datetime.date 对象转换为 pandas Timestamp,如下所示:
#!/usr/bin/env python3
# coding: utf-8
import pandas as pd
import datetime
# create a datetime data object
d_time = datetime.date(2010, 11, 12)
# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')
# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)
# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)
# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)
Run Code Online (Sandbox Code Playgroud)
小智 6
我使用了 Filomeno Gonzalez 推荐的方法,尽管略有不同:
data['date'] = data['date'].apply(lambda x: x.date())
Run Code Online (Sandbox Code Playgroud)
小智 6
from datetime import datetime
time = datetime.fromtimestamp(1676266245263 / 1000)
Run Code Online (Sandbox Code Playgroud)
输出示例:2023-02-13 05:30:45.263000
假设时间列是时间戳整数毫秒格式
1 天 = 86400000 毫秒
干得好:
day_divider = 86400000
df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format
df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
82823 次 |
| 最近记录: |