[英]converting dataframe column from object to date not datetime
I am using python version 3.7. 我使用的是python版本3.7。
I have a dataframe, df that contains one column called TDate. 我有一个数据帧,df包含一个名为TDate的列。
The column looks like below. 该列如下所示。
2019-01-01 00:00:00
2019-01-02 00:00:00
2019-01-03 00:00:00
2019-01-04 00:00:00
When I do df.dtypes it tell me the column is of type object. 当我做df.dtypes时它告诉我列是object类型。
I then have the line below, 我接下来就行,
myDates = pd.to_datetime(df['TDate']) myDates = pd.to_datetime(df ['TDate'])
So myDates is a pandas Series. 所以myDates是一个熊猫系列。
However if I access one element of this myDates series and check the type it tells me it is a libs.tslib.timestamps.Timestamp 但是,如果我访问此myDates系列的一个元素并检查其类型,它告诉我它是一个libs.tslib.timestamps.Timestamp
I just want to convert the original dataframe column from an object to a date in the format yyyy-mm-dd. 我只想将原始数据帧列从对象转换为格式为yyyy-mm-dd的日期。 What is the best way of doing this? 这样做的最佳方式是什么?
I looked at converting a timestamp to a date but that didn't work as the timestamp is a string literal not a integer. 我考虑将时间戳转换为日期,但由于时间戳是字符串文字而不是整数,因此不起作用。
Use Series.dt.floor
for remove time information from column (or better it is set to default 00:00:00
value in each datetime): 使用Series.dt.floor
从列中删除时间信息(或者更好地将其设置为每个日期时间的默认值00:00:00
):
myDates = pd.to_datetime(df['TDate']).dt.floor('d')
#for save to same column
#df['TDate'] = pd.to_datetime(df['TDate']).dt.floor('d')
Or Series.dt.normalize
: 或者Series.dt.normalize
:
myDates = pd.to_datetime(df['TDate']).dt.normalize()
#for save to same column
#df['TDate'] = pd.to_datetime(df['TDate']).dt.normalize()
If use: 如果使用:
myDates = pd.to_datetime(df['TDate']).dt.date
then output is python dates objects, so most datetimelike functions failed. 然后输出是python日期对象,因此大多数类似datetime的函数都失败了。
此代码段会将时间戳转换为日期
df['TDate']= pd.to_datetime(df['TDate']).dt.date
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.