Pandas:将时间戳转换为datetime.date

von4xj4u  于 2022-11-05  发布在  其他
关注(0)|答案(7)|浏览(184)

我有一个时间戳数据的Pandas列

In [27]: train["Original_Quote_Date"][6] 
Out[27]: Timestamp('2013-12-25 00:00:00')

如何检查这些对象与类型为datetime.date的对象的等价性

datetime.date(2013, 12, 25)
66bbxpm5

66bbxpm51#

使用.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

要与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)
dddzy1tm

dddzy1tm2#

从panda 0.20.3开始,使用.to_pydatetime()将任何pandas.DateTimeIndex示例转换为Python datetime.datetime

mlnl4t2r

mlnl4t2r3#

假定时间列采用时间戳整数毫秒格式
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
t9aqgxwy

t9aqgxwy4#

您可以将一个datetime.date对象转换为一个panda时间戳,如下所示:


# !/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)
llycmphe

llycmphe5#

这是从IBM coursera教程中得到的。

data['date'] = data['TimeStamp'].apply(lambda d: datetime.date.fromtimestamp(d))
q5lcpyga

q5lcpyga6#

我采用了菲洛梅诺·冈萨雷斯(Filomeno Gonzalez)推荐的方法,尽管有一点小改动:

data['date'] = data['date'].apply(lambda x: x.date())
chhkpiq4

chhkpiq47#

如果我有一个带有时间戳列(1546300800000, 1546301100000, 1546301400000, 1546301700000, 1546302000000)的PandasDataFrame,并且我想将其转换为日期时间格式

import datetime

df['date'] = df['date'].apply(lambda x: datetime.datetime.fromtimestamp(x/1000.0))

这将返回格式为2019-01-01 00:00:00, 2019-01-01 00:05:00, 2019-01-01 00:10:00, 2019-01-01 00:15:00, 2019-01-01 00:20:00 ...等的列
除以1000,将ms转换为s,如here所述

相关问题