【问题标题】:Python datetime problem converting time formatPython datetime问题转换时间格式
【发布时间】:2020-04-06 05:29:46
【问题描述】:

我想转换以下位于熊猫数据框列中的时间格式

100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400

我想将以前的时间格式转换为标准时间格式 HH:MM 如下

01:00
02:00
03:00
...
15:00
16:00
...
22:00
23:00
00:00

如何在 python 中做到这一点?

提前谢谢你

【问题讨论】:

  • 类似df['col2'] = pd.to_datetime(df['col1'],format='%H%M')
  • 感谢您的回复。我不工作,因为棘手的部分是 2400 小时格式。我想将该格式更改为 00:00。

标签: python pandas datetime


【解决方案1】:

这将为您提供一个带有 datetime64[ns] 和 object dtype 列的 df:

import pandas as pd

df = pd.read_csv('hm.txt', sep=r"[ ]{2,}", engine='python', header=None, names=['pre'])

df['pre_1'] = df['pre'].astype(str).str.replace('00', '')

df['datetime_dtype'] = pd.to_datetime(df['pre_1'], format='%H', exact=False)

df['str_dtype'] = df['datetime_dtype'].astype(str).str[11:16]

print(df.head(5))

    pre datetime_dtype  str_dtype
0   1   1900-01-01 01:00:00 01:00
1   2   1900-01-01 02:00:00 02:00
2   3   1900-01-01 03:00:00 03:00
3   4   1900-01-01 04:00:00 04:00
4   5   1900-01-01 05:00:00 05:00 

print(df.dtypes)

pre                       object
datetime_dtype    datetime64[ns]
str_dtype                 object
dtype: object

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 2014-10-26
    • 2018-11-12
    • 2011-05-29
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2021-10-31
    • 2012-03-27
    相关资源
    最近更新 更多