如何在python中重新排列日期

时间:2015-09-01 08:49:37

标签: python datetime pandas

我在pandas数据框中有一个列,如下所示:

test1.Received
Out[9]: 
0      01/01/2015 17:25
1      02/01/2015 11:43
2      04/01/2015 18:21
3      07/01/2015 16:17
4      12/01/2015 20:12
5      14/01/2015 11:09
6      15/01/2015 16:05
7      16/01/2015 21:02
8      26/01/2015 03:00
9      27/01/2015 08:32
10     30/01/2015 11:52 

这表示时间戳为日月年小时分钟。我想将日期重新安排为年月日小时分钟。所以它看起来像:

test1.Received
Out[9]: 
0      2015/01/01 17:25
1      2015/01/02 11:43
...

3 个答案:

答案 0 :(得分:1)

只需使用pd.to_datetime:

即可
In [33]:
import pandas as pd
pd.to_datetime(df['date'])
Out[33]:
index
0    2015-01-01 17:25:00
1    2015-02-01 11:43:00
2    2015-04-01 18:21:00
3    2015-07-01 16:17:00
4    2015-12-01 20:12:00
5    2015-01-14 11:09:00
6    2015-01-15 16:05:00
7    2015-01-16 21:02:00
8    2015-01-26 03:00:00
9    2015-01-27 08:32:00
10   2015-01-30 11:52:00
Name: date, dtype: datetime64[ns]

在你的情况下:

pd.to_datetime(test1['Received'])

应该正常工作

如果要更改显示格式,则需要解析为日期时间,然后apply`datetime.strftime:

In [35]:
import datetime as dt
pd.to_datetime(df['date']).apply(lambda x: dt.datetime.strftime(x, '%m/%d/%y %H:%M:%S'))

Out[35]:
index
0     01/01/15 17:25:00
1     02/01/15 11:43:00
2     04/01/15 18:21:00
3     07/01/15 16:17:00
4     12/01/15 20:12:00
5     01/14/15 11:09:00
6     01/15/15 16:05:00
7     01/16/15 21:02:00
8     01/26/15 03:00:00
9     01/27/15 08:32:00
10    01/30/15 11:52:00
Name: date, dtype: object

所以上面现在显示月/日/年,在你的情况下,以下应该有效:

pd.to_datetime(test1['Received']).apply(lambda x: dt.datetime.strftime(x, '%y/%m/%d %H:%M:%S'))

修改

您似乎需要将参数dayfirst=True传递给to_datetime

In [45]:
pd.to_datetime(df['date'], format('%d/%m/%y %H:%M:%S'), dayfirst=True).apply(lambda x: dt.datetime.strftime(x, '%m/%d/%y %H:%M:%S'))

Out[45]:
index
0     01/01/15 17:25:00
1     01/02/15 11:43:00
2     01/04/15 18:21:00
3     01/07/15 16:17:00
4     01/12/15 20:12:00
5     01/14/15 11:09:00
6     01/15/15 16:05:00
7     01/16/15 21:02:00
8     01/26/15 03:00:00
9     01/27/15 08:32:00
10    01/30/15 11:52:00
Name: date, dtype: object

答案 1 :(得分:1)

Pandas内置此功能,您可以指定日期时间格式 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html。 使用infer_datetime_format

>>> import pandas as pd
>>> i = pd.date_range('20000101',periods=100)
>>> df = pd.DataFrame(dict(year = i.year, month = i.month, day = i.day))
>>> pd.to_datetime(df.year*10000 + df.month*100 + df.day, format='%Y%m%d')
0    2000-01-01
1    2000-01-02
...
98   2000-04-08
99   2000-04-09
Length: 100, dtype: datetime64[ns]

答案 2 :(得分:1)

您可以使用datetime函数从字符串转换为字符串。

# converts to date 
datetime.strptime(date_string, 'DD/MM/YYYY HH:MM')  

# converts to your requested string format
datetime.strftime(date_string, "YYYY/MM/DD HH:MM:SS")