[英]How to drop the Year-Month-Date from a datetime series in python?
I have a datetime series, and I want to only keep the "Hour-Miniute-Second" strings in the series, and drop the Year-Month-Date strings. 我有一个日期时间系列,我想只保留系列中的“Hour-Miniute-Second”字符串,并删除Year-Month-Date字符串。 So what should I do? 所以我该怎么做?
original series: 原创系列:
0 2000-12-31 22:12:40
1 2000-12-31 22:35:09
2 2000-12-31 22:32:48
3 2000-12-31 22:04:35
4 2001-01-06 23:38:11
5 2000-12-31 22:37:48
……
target: 目标:
0 22:12:40
1 22:35:09
2 22:32:48
3 22:04:35
4 23:38:11
5 22:37:48
……
Preiviously the original series has been already translated from a unix timestamp series by using pandas.to_datetime()
. 很明显,原始系列已经通过使用pandas.to_datetime()
从unix时间戳系列中翻译pandas.to_datetime()
。 But I'm not able to use this method to reach my target:( 但我无法使用此方法达到我的目标:(
Any suggestions is appreciated! 任何建议表示赞赏!
Use dt.strftime
: 使用dt.strftime
:
#if necessary convert to datetime
#df['date'] = pd.to_datetime(df['date'])
print (df.dtypes)
date datetime64[ns]
dtype: object
df['time'] = df['date'].dt.strftime('%H:%M:%S')
print (df)
date time
0 2000-12-31 22:12:40 22:12:40
1 2000-12-31 22:35:09 22:35:09
2 2000-12-31 22:32:48 22:32:48
3 2000-12-31 22:04:35 22:04:35
4 2001-01-06 23:38:11 23:38:11
5 2000-12-31 22:37:48 22:37:48
Or cast to string
, split
and select second value of lists
by str[1]
: 或者转换为string
, split
并按str[1]
选择lists
的第二个值:
#if dtype of date column is object (obviously string), omit astype
df['time'] = df['date'].astype(str).str.split().str[1]
print (df)
date time
0 2000-12-31 22:12:40 22:12:40
1 2000-12-31 22:35:09 22:35:09
2 2000-12-31 22:32:48 22:32:48
3 2000-12-31 22:04:35 22:04:35
4 2001-01-06 23:38:11 23:38:11
5 2000-12-31 22:37:48 22:37:48
Using: datetime 使用: datetime
from datetime import datetime
your_datetime = "2017-01-01 23:00:00"
dt = datetime.strptime(your_datetime , "%Y-%m-%d %H:%M:%S").strftime('%H:%M:%S')
print dt
You've got some nice answer's already. 你已经有了一些不错的答案。 However, they store them as strings, and you might want to store them as actual datetime.time
objects: 但是,它们将它们存储为字符串,您可能希望将它们存储为实际的datetime.time
对象:
import pandas as pd
df = pd.DataFrame([
{'date': '2000-12-31 22:12:40'},
{'date': '2000-12-31 22:35:09'},
{'date': '2000-12-31 22:32:48'},
{'date': '2000-12-31 22:04:35'},
{'date': '2001-01-06 23:38:11'},
{'date': '2000-12-31 22:37:48'},
])
df['date'] = pd.to_datetime(df['date'])
df['time'] = df['date'].dt.time
print(df)
print(df['time'].dtype)
print(type(df['time'][0]))
date time
0 2000-12-31 22:12:40 22:12:40
1 2000-12-31 22:35:09 22:35:09
2 2000-12-31 22:32:48 22:32:48
3 2000-12-31 22:04:35 22:04:35
4 2001-01-06 23:38:11 23:38:11
5 2000-12-31 22:37:48 22:37:48
object
<class 'datetime.time'>
Edit: 编辑:
Noticed your target was without the date
column. 注意到您的目标没有date
列。 Add the following to the end: 将以下内容添加到最后:
del df['date']
print(df)
time
0 22:12:40
1 22:35:09
2 22:32:48
3 22:04:35
4 23:38:11
5 22:37:48
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.