[英]How to convert time object to datetime format in pandas (python)?
I am new to pandas and practicing some basic functionalities. 我是熊猫的新手,正在练习一些基本功能。 I have a CSV file which contains some data of every minute of some date.
我有一个CSV文件,其中包含某个日期每一分钟的一些数据。 After reading CSV,
df.head()
gives the following result : 读取CSV后,
df.head()
给出以下结果:
Time C1 C2 C3 C4 C5 C6
0 2016-05-25 03:15:00 0 0 0 0 0 0
1 2016-05-25 03:16:00 0 0 0 0 0 0
2 2016-05-25 03:17:00 0 0 2 0 0 0
3 2016-05-25 03:18:00 0 0 0 5 0 2
4 2016-05-25 03:19:00 0 0 0 0 0 5
I have used parse_dates
option of pd.read_csv
. 我已经使用
parse_dates
的选项pd.read_csv
。 Hence, Time is in datetime64[ns]
format. 因此,时间采用
datetime64[ns]
格式。 Since, the date is the same I don't want to have that on my column. 因为日期是相同的,所以我不想在列上显示该日期。 So, I use
所以,我用
df['Time']=df['Time'].dt.time
It does what I want but it changes the format to object
, which I didn't want. 它可以实现我想要的功能,但是它将格式更改为
object
,而我却不需要。 Upon suggestions of some other answers, I did the following : 根据其他答案的建议,我做了以下工作:
df['Time']=pd.to_datetime(df['Time'], format="%H:%M:%S")
df['Time'].head()
0 1900-01-01 03:15:00
1 1900-01-01 03:16:00
2 1900-01-01 03:17:00
3 1900-01-01 03:18:00
4 1900-01-01 03:19:00
Name: Time, dtype: datetime64[ns]
This converted the column into datetime64[ns]
but added an additional date. 这将列转换为
datetime64[ns]
但添加了另一个日期。 Is it possible to convert just time into datetime64[ns]
? 是否可以将仅时间转换为
datetime64[ns]
?
No, it is not possible. 不,不可能。 For datetimes always need dates.
对于日期时间,总是需要日期。
But if need working with times, better is use timedelta
s by strftime
for strings HH:MM:SS
with to_timedelta
: 但是,如果需要处理时间,最好将
strftime
timedelta
s用于带有to_timedelta
字符串HH:MM:SS
:
df['Time'] = pd.to_timedelta(df['Time'].dt.strftime('%H:%M:%S'))
print (df)
Time C1 C2 C3 C4 C5 C6
0 03:15:00 0 0 0 0 0 0
1 03:16:00 0 0 0 0 0 0
2 03:17:00 0 0 2 0 0 0
3 03:18:00 0 0 0 5 0 2
4 03:19:00 0 0 0 0 0 5
print (df.dtypes)
Time timedelta64[ns]
C1 int64
C2 int64
C3 int64
C4 int64
C5 int64
C6 int64
dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.