Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将datetime更改为正常格式?_Python_Pandas_Datetime - Fatal编程技术网

Python 如何将datetime更改为正常格式?

Python 如何将datetime更改为正常格式?,python,pandas,datetime,Python,Pandas,Datetime,我有这样的数据 但每次我想更改日期格式或使用它显示的日期时,小时应为0…23 如何将所有数据更改为正常格式?我将对此进行两次分析: In [11]: dates = ['2015/01/04 23:59', '2015/01/04 24:00', '2015/01/05 00:01', '2015/01/05 00:02', '2015/01/05 00:03', '2015/01/05 00:04', '2015/01/05 00:05'] 首先,我使用通常的方法(您不必在这里传递forma

我有这样的数据 但每次我想更改日期格式或使用它显示的日期时,小时应为0…23
如何将所有数据更改为正常格式?

我将对此进行两次分析:

In [11]: dates = ['2015/01/04 23:59', '2015/01/04 24:00', '2015/01/05 00:01', '2015/01/05 00:02', '2015/01/05 00:03', '2015/01/05 00:04', '2015/01/05 00:05']
首先,我使用通常的方法(您不必在这里传递format参数)

第二次仅在小时数为24时解析(并将天添加到结果中):

现在,您可以用第二个结果填充第一个结果:

In [16]: dates1.fillna(dates2)
Out[16]:
0   2015-01-04 23:59:00
1   2015-01-05 00:00:00
2   2015-01-05 00:01:00
3   2015-01-05 00:02:00
4   2015-01-05 00:03:00
5   2015-01-05 00:04:00
6   2015-01-05 00:05:00
dtype: datetime64[ns]
见此:

您可以使用strtime:

  • %小时(24小时格式)
  • %分钟
  • %I-小时(12小时格式)
  • %下午-上午或下午

您所说的正常格式是什么意思?午夜应该显示为00:00而不是24:00。
In [14]: dates2 = pd.Series(pd.to_datetime(dates, format="%Y/%m/%d 24:%M", errors='coerce')) + pd.offsets.Day(1)

In [15]: dates2
Out[15]:
0          NaT
1   2015-01-05
2          NaT
3          NaT
4          NaT
5          NaT
6          NaT
dtype: datetime64[ns]
In [16]: dates1.fillna(dates2)
Out[16]:
0   2015-01-04 23:59:00
1   2015-01-05 00:00:00
2   2015-01-05 00:01:00
3   2015-01-05 00:02:00
4   2015-01-05 00:03:00
5   2015-01-05 00:04:00
6   2015-01-05 00:05:00
dtype: datetime64[ns]
time = "15:45" # 24h format (military) 
formaT = datetime.datetime.strptime(time, ,'%H:%M').strftime('%I:%M %p')