我的数据框df中有一个DateTime列,如下所示:
DateTime
3/1/2016 12:15:00 AM
3/1/2016 12:30:00 AM
3/1/2016 12:45:00 AM
3/1/2016 1:00:00 AM
3/1/2016 1:15:00 AM
3/1/2016 1:30:00 AM
3/1/2016 1:45:00 AM
3/1/2016 2:00:00 AM
3/1/2016 2:15:00 AM
我想将其转换为以下格式,即24小时格式,如下所示:
03-01-2016 12:15:00
我该怎么做?
答案 0 :(得分:3)
这应该有效:
0 01-03-2016 00:15:00
1 01-03-2016 00:30:00
2 01-03-2016 00:45:00
3 01-03-2016 01:00:00
4 01-03-2016 01:15:00
5 01-03-2016 01:30:00
6 01-03-2016 01:45:00
7 01-03-2016 02:00:00
8 01-03-2016 02:15:00
Name: DateTime, dtype: object
输出:
<star :value="{{ $data['rating'] }}" :user="{{ $data['user_id'] }}"></star>
<!-- ^^ syntax error -->
答案 1 :(得分:2)
您只能使用to_datetime
:
print (df)
DateTime
0 3/1/2016 12:15:00 AM
1 3/1/2016 12:30:00 AM
2 3/1/2016 12:45:00 AM
3 3/1/2016 1:00:00 AM
4 3/1/2016 1:15:00 AM
5 3/1/2016 1:30:00 AM
6 3/1/2016 1:45:00 AM
7 3/1/2016 2:00:00 AM
8 3/1/2016 2:15:00 PM <-date is changed for better testing
df.DateTime = pd.to_datetime(df.DateTime)
print (df)
DateTime
0 2016-03-01 00:15:00
1 2016-03-01 00:30:00
2 2016-03-01 00:45:00
3 2016-03-01 01:00:00
4 2016-03-01 01:15:00
5 2016-03-01 01:30:00
6 2016-03-01 01:45:00
7 2016-03-01 02:00:00
8 2016-03-01 14:15:00
编辑:
然后需要参数errors='coerce'
来将有问题的值替换为NaT
:
print (df)
DateTime
0 3/1/2016 28:15:00 AM <- wrong date
1 3/1/2016 12:30:00 AM
2 3/1/2016 12:45:00 AM
3 3/1/2016 1:00:00 AM
4 3/1/2016 1:15:00 AM
5 3/1/2016 1:30:00 AM
6 3/1/2016 1:45:00 AM
7 3/1/2016 2:00:00 AM
8 3/1/2016 2:15:00 PM
df.DateTime = pd.to_datetime(df.DateTime, errors='coerce')
print (df)
DateTime
0 NaT
1 2016-03-01 00:30:00
2 2016-03-01 00:45:00
3 2016-03-01 01:00:00
4 2016-03-01 01:15:00
5 2016-03-01 01:30:00
6 2016-03-01 01:45:00
7 2016-03-01 02:00:00
8 2016-03-01 14:15:00
要检查有问题的值,请使用boolean indexing
:
print (df[pd.to_datetime(df.DateTime, errors='coerce').isnull()])
DateTime
0 3/1/2016 28:15:00 AM