【问题标题】:Unknown string format pd.to_datetime in Python. Having issues trying to convert this format to a datetime formatPython 中未知的字符串格式 pd.to_datetime。尝试将此格式转换为日期时间格式时遇到问题
【发布时间】:2021-01-08 18:45:39
【问题描述】:

我的 DF 中的列标题采用以下格式 -->

df_weather.columns

['Max-09-23', 'Min-09-23', 'Max-09-24', 'Min-09-24', 'Max-09-25',
       'Min-09-25', 'Max-09-26', 'Min-09-26', 'Max-09-27', 'Min-09-27',
       'Max-09-28', 'Min-09-28', 'Max-09-29', 'Min-09-29', 'Max-09-30',
       'Min-09-30', 'Max-10-01', 'Min-10-01', 'Max-10-02', 'Min-10-02']

我想将它们转换为日期时间格式,但最小值/最大值会导致问题。任何帮助表示赞赏。

【问题讨论】:

  • 他们应该得到什么日期?
  • 您好,欢迎来到 stackoverflow。另请发布您已经尝试解决的问题
  • 最大/最小-月-日
  • 我已经尝试了几种不同的日期时间和解析字符串的方法,但没有运气......
  • 你想要的列名格式是什么?

标签: python pandas datetime python-datetime python-dateutil


【解决方案1】:

一种选择可能是将“Min”/“Max”替换为特定年份并根据结果创建日期时间索引:

import pandas as pd

# let's create a dummy df...
cols = ['Max-09-23', 'Min-09-23', 'Max-09-24', 'Min-09-24', 'Max-09-25',
       'Min-09-25', 'Max-09-26', 'Min-09-26', 'Max-09-27', 'Min-09-27',
       'Max-09-28', 'Min-09-28', 'Max-09-29', 'Min-09-29', 'Max-09-30',
       'Min-09-30', 'Max-10-01', 'Min-10-01', 'Max-10-02', 'Min-10-02']
df_weather = pd.DataFrame({k: [0,0] for k in cols})

# set a default year...
year = '2020'

# to datetime...
dti = pd.to_datetime(df_weather.columns.str.replace('(Max)|(Min)', year))

dti
DatetimeIndex(['2020-09-23', '2020-09-23', '2020-09-24', '2020-09-24',
               '2020-09-25', '2020-09-25', '2020-09-26', '2020-09-26',
               '2020-09-27', '2020-09-27', '2020-09-28', '2020-09-28',
               '2020-09-29', '2020-09-29', '2020-09-30', '2020-09-30',
               '2020-10-01', '2020-10-01', '2020-10-02', '2020-10-02'],
              dtype='datetime64[ns]', freq=None)

否则,您也可以替换为 "" 并转换为具有定义格式 (format="-%m-%d") 的日期时间。但这会添加一个默认年份 1900。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2015-12-12
    相关资源
    最近更新 更多